"""
v0 script written by Myriam Benisty and Stefano Facchini (Feb 2st 2022)
v1 version adapted by Stefano Facchini and Myriam Benisty (Mar 2nd 2022)
v2 version adapted to include ACA data by Jane Huang and compacted code by Gianni Cataldi (May 19th 2022)
v3 (current version) includes EB alignment by Ryan Loomis and Richard Teague (Aug 2022)


This script is written for CASA 6.2.1.7. 
It can easily be adapted to other versions of CASA, e.g. by modifying the fixvis task to phaseshift task.

The numba package is used for the alignment script, but it is not necessary (it helps with the speed-up)

The scripts are written to be compatible mpicasa.
However, after testingthe exoALMA collaboration decided not to use mpicasa in any of the calibration scripts,
since they realized that differences in the results between casa and mpicasa could arise.

Person in charge for this source:
G. Cataldi

"""

import os
import numpy as np
import shutil

#path to your local copy of the gihub repository
#(make sure to do a 'git pull' to have the most up-to-date version)
github_path = '/users/gcataldi/calibration_scripts'
import sys
sys.path.append('/lustre/cv/projects/exoALMA/ALMA_PL_calibrated_data/analysis_utils/analysis_scripts/')
import analysisUtils as au
sys.path.append(github_path)
import alignment
execfile(os.path.join(github_path,'reduction_utils_exoalma.py'))
#increase the number of figures that can be open before issuing a warning
matplotlib.rcParams.update({'figure.max_open_warning':80})

prefix = 'J1604'

data_folderpath = '/lustre/cv/projects/exoALMA/ALMA_PL_calibrated_data/J1604-2130'
TM_names = {'LB':'TM1','SB':'TM2', 'ACA':'ACA'}
PL_calibrated_vis = {key:os.path.join(data_folderpath,f'{TM_name}/calibrated_final.ms')
                     for key,TM_name in TM_names.items()}

for baseline_key,TM_name in TM_names.items():
    listobs(
        vis=PL_calibrated_vis[baseline_key],
        listfile=f'{prefix}_{TM_name}_calibrated_final.ms.txt',
        overwrite=True)

# System properties.
incl =  6 # deg, Dong17
PA   = 80   # deg, Dong17
v_sys = 4.6 # km/s; use the one from listobs

# Whether to run tclean in parallel or not.
use_parallel = True

fields = {'ACA':'RXJ1604.3-2130','SB':'RXJ1604.3-2130','LB':'RXJ1604.3-2130'}
number_of_EBs = {'ACA':4,'SB':2,'LB':3}

for baseline_key,vis in PL_calibrated_vis.items():
    split_all_obs(msfile=vis,nametemplate=f'{prefix}_{baseline_key}_EB')

for baseline_key,n_EB in number_of_EBs.items():
    for i in range(n_EB):
        vis = f'{prefix}_{baseline_key}_EB{i}.ms'
        listobs(vis=vis,listfile=f'{vis}.txt',overwrite=True)

"""
Check that spws and field numbering is what you expect them to be now from the listobs files
In particular, make sure that there are 4 spws and that there is a single field with
field ID = 0
"""

# Line rest frequencies from splatalogue (https://splatalogue.online)
rest_freq_12CO = 345.79598990e9 #J=3-2
rest_freq_13CO = 330.58796530e9 #J=3-2 (ignoring splitting)
rest_freq_CS   = 342.88285030e9 #J=7-6

data_params_LB = {f'LB{i}': {'vis' : f'{prefix}_LB_EB{i}.ms',
                             'name' : f'LB_EB{i}',
                             'field' : fields['LB'],
                             'line_spws': np.array([0,2,3]), # list of spws containing lines
                             'line_freqs': np.array([rest_freq_13CO,rest_freq_CS,rest_freq_12CO]), #frequencies (Hz) corresponding to line_spws
                             'cont_spws': None,
                             'width_array': None,
                             }
               for i in range(number_of_EBs['LB'])}

data_params_SB = {f'SB{i}': {'vis' : f'{prefix}_SB_EB{i}.ms',
                             'name' : f'SB_EB{i}',
                             'field' : fields['SB'],
                             'line_spws': np.array([0,2,3]), # list of spws containing lines
                             'line_freqs': np.array([rest_freq_13CO,rest_freq_CS,rest_freq_12CO]), #frequencies (Hz) corresponding to line_spws
                             'cont_spws': None,
                             'width_array': None,
                             }
                  for i in range(number_of_EBs['SB'])}

data_params_ACA = {f'ACA{i}': {'vis' : f'{prefix}_ACA_EB{i}.ms',
                               'name' : f'ACA_EB{i}',
                               'field' : fields['ACA'],
                               'line_spws': np.array([0,2,3]), # list of spws containing lines
                               'line_freqs': np.array([rest_freq_13CO,rest_freq_CS,rest_freq_12CO]), #frequencies (Hz) corresponding to line_spws
                               'cont_spws': None,
                               'width_array': None,
                               }
                   for i in range(number_of_EBs['ACA'])}

data_params = data_params_LB.copy()
data_params.update(data_params_SB)
data_params.update(data_params_ACA)


figures_foldername = 'figures'
os.mkdir(figures_foldername)

def get_figures_folderpath(foldername):
    return os.path.join(figures_foldername,foldername)

def make_figures_folder(folderpath):
    if os.path.isdir(folderpath):
        print(f'going to deleted folder {folderpath} and its content')
        valid_answer = 'yes'
        answer = input(f'to confirm, type \'{valid_answer}\': ')
        if answer == valid_answer:
            shutil.rmtree(folderpath)
        else:
            print('aborting')
            return
    os.mkdir(folderpath)
    return folderpath

preselfcal_amp_figures_folder = get_figures_folderpath('1_preselfcal_amp_figures')
make_figures_folder(preselfcal_amp_figures_folder)

#adjust these plot ranges according to your data
uvdist_amp_plotranges = {'ACA':[0,200,0,0.45], #xmin,xmax,ymin,ymax; x=uvdist,y=amp
                         'SB':[0,800,0,0.35],
                         'LB':[0,3500,0,0.35]}

for params in data_params.values():
    plotms(vis=params['vis'],
            xaxis='channel',
            yaxis='amplitude',
            field=params['field'],
            ydatacolumn='data',
            avgtime='1e8',
            avgscan=True,
            avgbaseline=True,
            #There is a bug in plotms that plots the data wrongly if there is unequal flagging
            #between the polarisations
            #the bug occurs if we plot amp and we average over baselines
            #thus we color by polarization such that
            #we easily identify this issue
            #if you find issues, then try plotting XX and YY polarisation separately
            #to verify that it is only a plotms bug and not a problem with the data
            coloraxis='corr',
            iteraxis='spw',
            showgui = False,
            overwrite=True,
            exprange='all',
            plotfile=os.path.join(preselfcal_amp_figures_folder,
                                  prefix+'_'+params['name']+'_chan-v-amp_preselfcal.png'))
    baseline_key = params['name'].split('_')[0]
    plotms(vis=params['vis'],
            xaxis='UVdist',
            yaxis='amplitude',
            spw='1',#continuum spw
            field=params['field'],
            ydatacolumn='data',
            avgtime='1e8',
            avgscan=True,
            avgchannel='3840',
            showgui = False,
            overwrite=True,
            plotrange=uvdist_amp_plotranges[baseline_key],
            plotfile=os.path.join(preselfcal_amp_figures_folder,
                                  prefix+'_'+params['name']+'_uvdist-v-amp_cont_spw_preselfcal.png'))


for params in data_params.values():
    flagchannels_string = get_flagchannels(ms_dict=params,output_prefix=prefix,
                                           velocity_range = np.array([-15., 15.])+v_sys)
    avg_cont(ms_dict=params, output_prefix=prefix, flagchannels = flagchannels_string,
             contspws = params['cont_spws'], width_array=params['width_array'])

"""
Double-check that the channels idenfified are at the center of the spws,
due to a potential issue with the data_desc_id key in the ms table of some programs
"""
# Flagchannels input string for LB_EB0: '0:834~3002, 2:798~3046, 3:782~3049'
# Flagchannels input string for LB_EB1: '0:834~3002, 2:798~3046, 3:782~3049'
# Flagchannels input string for LB_EB2: '0:834~3002, 2:798~3046, 3:781~3049'
# Flagchannels input string for SB_EB0: '0:838~3006, 2:793~3042, 3:790~3058'
# Flagchannels input string for SB_EB1: '0:837~3005, 2:793~3042, 3:788~3056'
# Flagchannels input string for ACA_EB0: '0:963~3131, 2:921~3170, 3:915~3183'
# Flagchannels input string for ACA_EB1: '0:963~3131, 2:921~3170, 3:915~3182'
# Flagchannels input string for ACA_EB2: '0:963~3131, 2:921~3169, 3:915~3183'
# Flagchannels input string for ACA_EB3: '0:963~3131, 2:920~3169, 3:916~3184'


preselfcal_initcont_amp_folder = get_figures_folderpath(
                                  '2_preselfcal_initcont_amp_figures')
make_figures_folder(preselfcal_initcont_amp_folder)

#take care to choose uv ranges where the amp is non-zero
uv_ranges = {'LB':'165~195m','SB':'165~195m','ACA':'0~50m'}

for params in data_params.values():
    vis = prefix+'_'+params['name']+'_initcont.ms'
    baseline_key = params['name'].split('_')[0]
    plotms(vis=vis,
           xaxis='UVdist',
           overwrite=True,
           yaxis='amp',
           coloraxis='spw',
           avgtime='1e8',
           avgscan=True,
           showgui=False,
           plotrange=uvdist_amp_plotranges[baseline_key],
           plotfile=os.path.join(preselfcal_initcont_amp_folder,
                                 prefix+'_'+params['name']+'_uvdist-v-amp_initcont_preselfcal.png'))

    plotms(vis=vis,
            xaxis='time',
            yaxis='amp',
            avgspw=True,
            uvrange=uv_ranges[baseline_key],
            avgchannel='10000',
            avgbaseline=True,
            coloraxis='corr',
            showgui=False,
            overwrite=True,
            plotfile=os.path.join(preselfcal_initcont_amp_folder,
                                  prefix+'_'+params['name']+'_amp_v_time_initcont_preselfcal.png')
            )

preselfcal_images_folder = get_figures_folderpath('3_preselfcal_images')
make_figures_folder(preselfcal_images_folder)

############# shift phase center
#from the images below we see that there is a significant offset between the disk
#center and the phase center
#so let's first of all shift the phase center to the disk center
#(this is not strictly required for the self-cal, but it's convenient, so we
#don't need to specify offsets when plotting azimuthally averaged visibilities
#etc.)
disk_center_ref = f'{prefix}_SB_EB1_initcont.ms'
diagnostic_plot_filename = os.path.join(preselfcal_images_folder,
                                        'disk_center_diagnostics.png')
continuum_spwid = 1
#for SB, I use npix=102 and cell_size=0.1
disk_center_fit = alignment.find_disk_center(
                                ms=disk_center_ref,npix=102,
                                cell_size=0.1,spwid=continuum_spwid,
                                plot_diagnostics=True,
                                diagnostic_plot_filename=diagnostic_plot_filename)
print('shift of disk center vs phase center: ',disk_center_fit['fitted offset'])
# {'fitted offset': array([-0.28268446, -0.66728353]),
#  'disk center': 'ICRS 16h04m21.6397s -21d30m29.0713s'}
fitted_disk_center = 'ICRS 16h04m21.6397s -21d30m29.0713s'

for params in data_params.values():
    vis = f'{prefix}_{params["name"]}_initcont.ms'
    #make a copy of the vis before shifting; this can be useful in the case I need
    #to determine the offset again
    shutil.copytree(src=vis,dst=vis[:-3]+'_before_phasecenter_shift.ms')
    fixvis(vis=vis,field=params['field'],phasecenter=fitted_disk_center)
    #re-generate listobs with updated phase centers
    listobs(vis=vis,listfile=f'{vis}.txt',overwrite=True)
###############################

""" Define simple masks and clean scales for imaging """
mask_pa = PA #position angle of mask in degrees
mask_semimajor = 2 #semimajor axis of mask in arcsec
mask_semiminor = mask_semimajor*np.cos(incl/180.*np.pi) #semiminor axis of mask in arcsec
mask_ra = '16h04m21.6397s'
mask_dec = '-21.30.29.0713'

mask_TM = f'ellipse[[{mask_ra},{mask_dec}], [{mask_semimajor:.3f}arcsec, {mask_semiminor:.3f}arcsec], {mask_pa:.1f}deg]'
# Cellsize: ~beam/6-7
LB_cellsize =  '0.015arcsec'
# Image size: ~primary beam 1.22*lam/A = 32'' with A=12m (19 arcsec)
LB_imsize = 1200 # primary beam
LB_scales = [0,8,15,30,80]

SB_cellsize =  '0.040arcsec'
SB_imsize = 400 # primary beam
SB_scales = [0,8,15,30]

noise_annulus_TM = f"annulus[[{mask_ra}, {mask_dec}],['4.arcsec', '6.arcsec']]"

mask_semimajor_ACA = 8 #semimajor axis of mask in arcsec
mask_semiminor_ACA = 8 #semiminor axis of mask in arcsec
mask_ACA = f'ellipse[[{mask_ra},{mask_dec}], [{mask_semimajor_ACA:.3f}arcsec, {mask_semiminor_ACA:.3f}arcsec], {mask_pa:.1f}deg]'
# Cellsize: ~beam/6-7, synthesized beam: ~3.3-5'' (ACA)
ACA_cellsize =  '0.5arcsec'
# Image size: ~primary beam 1.22*lam/A = 32'' with A=7m
ACA_imsize = 100 # primary beam

noise_annulus_ACA = f"annulus[[{mask_ra}, {mask_dec}],['11.arcsec', '18.arcsec']]"

#sizes in [arcsec] of the zoomed and overview plots of the output pngs
image_png_plot_sizes = {'LB':[3,10],'ACA':[10,30]}
image_png_plot_sizes['SB'] = image_png_plot_sizes['LB']


#EB0 has significantly larger noise, so I make the threshold EB-dependent
LB_threshold = {'LB0':f'{6*0.11}mJy','LB1':f'{6*0.08}mJy','LB2':f'{6*0.08}mJy'}
for EB_key,params in data_params_LB.items():
    imagename = prefix+'_'+params['name']+'_initcont_image'
    #delete_tclean_output(imagename)
    #clean down to 6 sigma
    tclean_wrapper(
                  vis=prefix+'_'+params['name']+'_initcont.ms',
                  imagename=imagename,
                  deconvolver='multiscale',
                  scales=LB_scales,
                  mask=mask_TM,
                  threshold=LB_threshold[EB_key],
                  cellsize=LB_cellsize,
                  imsize=LB_imsize,
                  parallel=use_parallel,
                  savemodel = 'modelcolumn')
    estimate_SNR(f'{imagename}.image',disk_mask=mask_TM,noise_mask=noise_annulus_TM)
    rms = imstat(imagename = f'{imagename}.image', region = noise_annulus_TM)['rms'][0]
    data_params_LB[EB_key]['rms'] = rms
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['LB'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=preselfcal_images_folder,
                       mask=f'{imagename}.mask',noise_annulus=noise_annulus_TM)

#J1604_LB_EB0_initcont_image.image
#Beam 0.139 arcsec x 0.099 arcsec (-72.77 deg)
#Flux inside disk mask: 209.54 mJy
#Peak intensity of source: 4.28 mJy/beam
#rms: 1.12e-01 mJy/beam
#Peak SNR: 38.29

#J1604_LB_EB1_initcont_image.image
#Beam 0.127 arcsec x 0.106 arcsec (-77.74 deg)
#Flux inside disk mask: 205.37 mJy
#Peak intensity of source: 4.17 mJy/beam
#rms: 8.14e-02 mJy/beam
#Peak SNR: 51.20

#J1604_LB_EB2_initcont_image.image
#Beam 0.128 arcsec x 0.095 arcsec (87.66 deg)
#Flux inside disk mask: 205.86 mJy
#Peak intensity of source: 4.13 mJy/beam
#rms: 7.74e-02 mJy/beam
#Peak SNR: 53.36


SB_threshold = {'SB0':f'{6*0.36}mJy','SB1':f'{6*0.19}mJy'}

for EB_key,params in data_params_SB.items():
    imagename = prefix+'_'+params['name']+'_initcont_image'
    #delete_tclean_output(imagename)
    #clean down to 6 sigma
    tclean_wrapper(
                  vis=prefix+'_'+params['name']+'_initcont.ms',
                  imagename=imagename,
                  deconvolver='multiscale',
                  scales=SB_scales,
                  mask=mask_TM,
                  threshold=SB_threshold[EB_key],
                  cellsize=SB_cellsize,
                  imsize=SB_imsize,
                  parallel=use_parallel,
                  savemodel = 'modelcolumn')
    estimate_SNR(f'{imagename}.image',disk_mask=mask_TM,noise_mask=noise_annulus_TM)
    rms = imstat(imagename = f'{imagename}.image', region = noise_annulus_TM)['rms'][0]
    data_params_SB[EB_key]['rms'] = rms
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['SB'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=preselfcal_images_folder,
                       mask=f'{imagename}.mask',noise_annulus=noise_annulus_TM)

#J1604_SB_EB0_initcont_image.image
#Beam 0.509 arcsec x 0.394 arcsec (79.52 deg)
#Flux inside disk mask: 171.75 mJy
#Peak intensity of source: 23.10 mJy/beam
#rms: 3.69e-01 mJy/beam
#Peak SNR: 62.60

#J1604_SB_EB1_initcont_image.image
#Beam 0.540 arcsec x 0.419 arcsec (78.15 deg)
#Flux inside disk mask: 194.32 mJy
#Peak intensity of source: 27.71 mJy/beam
#rms: 1.88e-01 mJy/beam
#Peak SNR: 147.60



ACA_threshold = {'ACA0':f'{6*5}mJy','ACA1':f'{6*3.4}mJy','ACA2':f'{6*4.3}mJy',
                 'ACA3':f'{6*4.7}mJy'}
for EB_key,params in data_params_ACA.items():
    imagename = prefix+'_'+params['name']+'_initcont_image'
    #delete_tclean_output(imagename)
    #clean down to 6 sigma
    tclean_wrapper(
                  vis=prefix+'_'+params['name']+'_initcont.ms',
                  imagename=imagename,
                  deconvolver='hogbom',
                  mask=mask_ACA,
                  threshold=ACA_threshold[EB_key],
                  cellsize=ACA_cellsize,
                  imsize=ACA_imsize,
                  parallel=use_parallel,
                  savemodel = 'modelcolumn')
    estimate_SNR(f'{imagename}.image', disk_mask = mask_ACA, noise_mask = noise_annulus_ACA)
    rms = imstat(imagename = f'{imagename}.image', region = noise_annulus_ACA)['rms'][0]
    data_params_ACA[EB_key]['rms'] = rms
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['ACA'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=preselfcal_images_folder,
                       mask=f'{imagename}.mask',noise_annulus=noise_annulus_ACA)
#J1604_ACA_EB0_initcont_image.image
#Beam 4.613 arcsec x 4.015 arcsec (-49.25 deg)
#Flux inside disk mask: 157.00 mJy
#Peak intensity of source: 170.81 mJy/beam
#rms: 5.04e+00 mJy/beam
#Peak SNR: 33.87
#J1604_ACA_EB1_initcont_image.image
#Beam 4.799 arcsec x 4.535 arcsec (-84.94 deg)
#Flux inside disk mask: 179.44 mJy
#Peak intensity of source: 186.98 mJy/beam
#rms: 3.06e+00 mJy/beam
#Peak SNR: 61.05
#J1604_ACA_EB2_initcont_image.image
#Beam 4.550 arcsec x 3.389 arcsec (-70.20 deg)
#Flux inside disk mask: 158.60 mJy
#Peak intensity of source: 166.87 mJy/beam
#rms: 3.96e+00 mJy/beam
#Peak SNR: 42.14
#J1604_ACA_EB3_initcont_image.image
#Beam 4.816 arcsec x 3.568 arcsec (-78.55 deg)
#Flux inside disk mask: 163.34 mJy
#Peak intensity of source: 169.57 mJy/beam
#rms: 4.15e+00 mJy/beam
#Peak SNR: 40.83


######
# SELF-CAL INDIVIDUAL EBs
######
""" Self-calibration parameters """
single_EB_contspws = '0~3'

single_EB_spw_mapping = [0,0,0,0]

EB_selfcal_folder = get_figures_folderpath('4_individual_EB_selfcal figures')
make_figures_folder(EB_selfcal_folder)


""" One round of phase-only self-cal """
for params in data_params.values():
    single_EB_p1 = prefix+'_'+params['name']+'_initcont.p1'
    os.system('rm -rf '+single_EB_p1)
    gaincal(vis=prefix+'_'+params['name']+'_initcont.ms',caltable=single_EB_p1,
            gaintype='T', spw=single_EB_contspws,combine='scan,spw',
            calmode='p', solint='inf', minsnr=4., minblperant=3)

    """ Print calibration png file """
    plotms(single_EB_p1,
            xaxis='time',
            yaxis='GainPhase',
            overwrite=True,
            showgui=False,
            plotfile=os.path.join(EB_selfcal_folder,
                                  prefix+'_'+params['name']+'_initcont_gain_p1_phase_vs_time.png'))

    """ Apply the solutions """
    applycal(vis=prefix+'_'+params['name']+'_initcont.ms', spw=single_EB_contspws,
             spwmap=single_EB_spw_mapping,gaintable=[single_EB_p1], interp='linearPD',
             applymode='calonly', calwt=True)
    split(vis=prefix+'_'+params['name']+'_initcont.ms',
          outputvis=prefix+'_'+params['name']+'_initcont_selfcal.ms',
          datacolumn='corrected')


### Image self-cal'd EBs ###

for EB_key,params in data_params_LB.items():
    imagename = prefix+'_'+params['name']+'_initcont_selfcal_image'
    tclean_wrapper(
                  vis=prefix+'_'+params['name']+'_initcont_selfcal.ms',
                  imagename=imagename,
                  deconvolver='multiscale',
                  scales=LB_scales,
                  mask=mask_TM,
                  threshold= LB_threshold[EB_key],
                  cellsize=LB_cellsize,
                  imsize=LB_imsize,
                  parallel=use_parallel,
                )
    estimate_SNR(f'{imagename}.image',disk_mask=mask_TM,noise_mask=noise_annulus_TM)
    rms = params['rms']
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['LB'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=EB_selfcal_folder,
                       mask=f'{imagename}.mask',noise_annulus=noise_annulus_TM)

#J1604_LB_EB0_initcont_selfcal_image.image
#Beam 0.139 arcsec x 0.099 arcsec (-72.77 deg)
#Flux inside disk mask: 210.35 mJy
#Peak intensity of source: 4.38 mJy/beam
#rms: 1.01e-01 mJy/beam
#Peak SNR: 43.23

#J1604_LB_EB1_initcont_selfcal_image.image
#Beam 0.127 arcsec x 0.106 arcsec (-77.74 deg)
#Flux inside disk mask: 206.63 mJy
#Peak intensity of source: 4.16 mJy/beam
#rms: 7.24e-02 mJy/beam
#Peak SNR: 57.46

#J1604_LB_EB2_initcont_selfcal_image.image
#Beam 0.128 arcsec x 0.095 arcsec (87.66 deg)
#Flux inside disk mask: 207.17 mJy
#Peak intensity of source: 4.17 mJy/beam
#rms: 6.99e-02 mJy/beam
#Peak SNR: 59.61

## Compute intensity ratio to check position shifts between different LB EBs before
#applying alignment
default(immath)
for params in data_params_LB.values():
    ref_image = prefix+'_LB_EB2_initcont_selfcal_image.image'
    imagename = prefix+'_'+params['name']+'_initcont_selfcal_image'
    os.system('rm -rf '+imagename+'.ratio')
    immath(imagename=[ref_image,imagename+'.image'],mode='evalexpr',
           outfile=imagename+'.ratio',
           expr='iif(IM0 > 3*'+str(data_params_LB['LB2']['rms'])+', IM1/IM0, 0)'
           )
    generate_image_png(f'{imagename}.ratio',plot_sizes=[2*mask_semimajor,2*mask_semimajor],
                       color_scale_limits=[0.5,1.5],image_units='ratio',
                       save_folder=EB_selfcal_folder)


for EB_key,params in data_params_SB.items():
    imagename = prefix+'_'+params['name']+'_initcont_selfcal_image'
    tclean_wrapper(
                 vis=prefix+'_'+params['name']+'_initcont_selfcal.ms',
                 imagename=imagename,
                 deconvolver='multiscale',
                 scales=SB_scales,
                 mask=mask_TM,
                 threshold=SB_threshold[EB_key],
                 cellsize=SB_cellsize,
                 imsize=SB_imsize,
                 parallel=use_parallel,
                )
    estimate_SNR(f'{imagename}.image',disk_mask=mask_TM,noise_mask=noise_annulus_TM)
    rms = params['rms']
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['SB'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=EB_selfcal_folder,
                       mask=f'{imagename}.mask',noise_annulus=noise_annulus_TM)

#J1604_SB_EB0_initcont_selfcal_image.image
#Beam 0.509 arcsec x 0.394 arcsec (79.52 deg)
#Flux inside disk mask: 180.40 mJy
#Peak intensity of source: 24.06 mJy/beam
#rms: 1.48e-01 mJy/beam
#Peak SNR: 162.75
#J1604_SB_EB1_initcont_selfcal_image.image
#Beam 0.540 arcsec x 0.419 arcsec (78.15 deg)
#Flux inside disk mask: 196.13 mJy
#Peak intensity of source: 27.73 mJy/beam
#rms: 9.32e-02 mJy/beam
#Peak SNR: 297.45


## Compute intensity ratio to check position shifts between different SB EBs before applying alignment
default(immath)
for params in data_params_SB.values():
    ref_image = prefix+'_SB_EB1_initcont_selfcal_image.image'
    imagename = prefix+'_'+params['name']+'_initcont_selfcal_image'
    os.system('rm -rf '+imagename+'.ratio')
    immath(imagename=[ref_image,imagename+'.image'],mode='evalexpr',
           outfile=imagename+'.ratio',
           expr='iif(IM0 > 3*'+str(data_params_SB['SB1']['rms'])+', IM1/IM0, 0)')
    generate_image_png(f'{imagename}.ratio',
                       plot_sizes=[2*mask_semimajor,2*mask_semimajor],
                       color_scale_limits=[0.5,1.5],image_units='ratio',
                       save_folder=EB_selfcal_folder)


for EB_key,params in data_params_ACA.items():
    imagename = prefix+'_'+params['name']+'_initcont_selfcal_image'
    tclean_wrapper(
                 vis=prefix+'_'+params['name']+'_initcont_selfcal.ms',
                 imagename=imagename,
                 deconvolver='hogbom',
                 mask=mask_ACA,
                 threshold=ACA_threshold[EB_key],
                 cellsize=ACA_cellsize,
                 imsize=ACA_imsize,
                 parallel=use_parallel,
                )
    estimate_SNR(f'{imagename}.image', disk_mask = mask_ACA, noise_mask = noise_annulus_ACA)
    rms = params['rms']
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['ACA'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=EB_selfcal_folder,
                       mask=f'{imagename}.mask',noise_annulus=noise_annulus_ACA)
#J1604_ACA_EB0_initcont_selfcal_image.image
#Beam 4.612 arcsec x 4.014 arcsec (-49.25 deg)
#Flux inside disk mask: 165.05 mJy
#Peak intensity of source: 172.81 mJy/beam
#rms: 2.91e+00 mJy/beam
#Peak SNR: 59.30

#J1604_ACA_EB1_initcont_selfcal_image.image
#Beam 4.799 arcsec x 4.535 arcsec (-84.92 deg)
#Flux inside disk mask: 181.46 mJy
#Peak intensity of source: 187.87 mJy/beam
#rms: 2.47e+00 mJy/beam
#Peak SNR: 76.03

#J1604_ACA_EB2_initcont_selfcal_image.image
#Beam 4.549 arcsec x 3.389 arcsec (-70.21 deg)
#Flux inside disk mask: 161.99 mJy
#Peak intensity of source: 169.70 mJy/beam
#rms: 2.69e+00 mJy/beam
#Peak SNR: 63.13

#J1604_ACA_EB3_initcont_selfcal_image.image
#Beam 4.816 arcsec x 3.568 arcsec (-78.57 deg)
#Flux inside disk mask: 166.46 mJy
#Peak intensity of source: 172.13 mJy/beam
#rms: 3.32e+00 mJy/beam
#Peak SNR: 51.78


## Compute intensity ratio to check position shifts between differnet ACA EBs before applying alignment
default(immath)
for params in data_params_ACA.values():
    ref_image = prefix+'_ACA_EB1_initcont_selfcal_image.image'
    imagename = prefix+'_'+params['name']+'_initcont_selfcal_image'
    os.system('rm -rf '+imagename+'.ratio')
    immath(imagename=[ref_image,imagename+'.image'],mode='evalexpr',
           outfile=imagename+'.ratio',
           expr='iif(IM0 > 3*'+str(data_params_ACA['ACA1']['rms'])+', IM1/IM0, 0)')
    generate_image_png(f'{imagename}.ratio',
                       plot_sizes=[2*mask_semimajor_ACA,2*mask_semimajor_ACA],
                       color_scale_limits=[0.5,1.5],image_units='ratio',
                       save_folder=EB_selfcal_folder)


######
# ALIGN DATA (go from *initcont_selfcal.ms to *initcont_shift.ms)
######

alignment_folder = get_figures_folderpath('5_alignment_figures')
make_figures_folder(alignment_folder)


#select the continuum spw with the large bandwidth
continuum_spw_id = 1
#cell_size defines the size of the uv grid
alignment_npix = {'LB':1024,'SB':102,'ACA':30}
alignment_cell_size = {'LB':0.01,'SB':0.1,'ACA':1.}


# Select the LB EB to act as the reference (usually the best SNR one).

reference_for_LB_alignment = f'{prefix}_LB_EB2_initcont_selfcal.ms'
assert 'LB' in reference_for_LB_alignment, 'you need to choose an LB EB for alignment of LB'

alignment_offsets = {}

# All the other EBs will be aligned to the reference_EB
# We also include the reference_EB itself to make sure the coordinate changes are
# copied over.

offset_LB_EBs = ['{}_{}_initcont_selfcal.ms'.format(prefix, params['name'])
                 for params in data_params_LB.values()]

alignment_plot_file_template = os.path.join(alignment_folder,
                                            'alignment_uv_grid.png')
# Find the relative offsets and update the phase centers for all offset_EBs.
alignment.align_measurement_sets(reference_ms=reference_for_LB_alignment,
                                 align_ms=offset_LB_EBs,npix=alignment_npix['LB'],
                                 cell_size=alignment_cell_size['LB'],
                                 spwid=continuum_spw_id,plot_uv_grid=True,
                                 plot_file_template=alignment_plot_file_template)
#New coordinates for J1604_LB_EB0_initcont_selfcal.ms
#requires a shift of [-0.034634,-0.0069779]

#New coordinates for J1604_LB_EB1_initcont_selfcal.ms
#requires a shift of [-0.037856,-0.0077817]

#New coordinates for J1604_LB_EB2_initcont_selfcal.ms
#no shift, reference MS


alignment_offsets['LB_EB0'] = [-0.034634,-0.0069779]
alignment_offsets['LB_EB1'] = [-0.037856,-0.0077817]
alignment_offsets['LB_EB2'] = [0,0] #ref EB

shifted_LB_EBs = [EB.replace('.ms','_shift.ms') for EB in offset_LB_EBs]

#to check if alignment worked, calculate shift again and verify that shifts are small
for shifted_ms in shifted_LB_EBs:
    if shifted_ms == reference_for_LB_alignment.replace('.ms','_shift.ms'):
        #skip the reference because the fitter will fail for unknown reason
        continue
    offset = alignment.find_offset(reference_ms=reference_for_LB_alignment,
                                   offset_ms=shifted_ms,npix=alignment_npix['LB'],
                                   cell_size=alignment_cell_size['LB'],
                                   spwid=continuum_spw_id)
    print(f'#offset for {shifted_ms}: ',offset)
#offset for J1604_LB_EB0_initcont_selfcal_shift.ms:  [-0.0001386  -0.00029297]
#offset for J1604_LB_EB1_initcont_selfcal_shift.ms:  [-2.41451103e-04  7.40712381e-05]

# Merge shifted LB EBs for aligning SB EBs
LB_concat_shifted = f'{prefix}_LB_concat_shifted.ms'
os.system(f'rm -rf {LB_concat_shifted}')
concat(vis=shifted_LB_EBs,concatvis=LB_concat_shifted,dirtol='0.1arcsec',
       copypointing=False)


# Align SB EBs to concat shifted LB EBs
reference_for_SB_alignment = LB_concat_shifted

offset_SB_EBs = ['{}_{}_initcont_selfcal.ms'.format(prefix, params['name'])
                 for params in data_params_SB.values()]

alignment.align_measurement_sets(reference_ms=reference_for_SB_alignment,
                                 align_ms=offset_SB_EBs,npix=alignment_npix['SB'],
                                 cell_size=alignment_cell_size['SB'],
                                 spwid=continuum_spw_id,plot_uv_grid=True,
                                 plot_file_template=alignment_plot_file_template)

#New coordinates for J1604_SB_EB0_initcont_selfcal.ms
#requires a shift of [0.0042348,0.032905]

#New coordinates for J1604_SB_EB1_initcont_selfcal.ms
#requires a shift of [0.016089,-0.0024655]

alignment_offsets['SB_EB0'] = [0.0042348,0.032905]
alignment_offsets['SB_EB1'] = [0.016089,-0.0024655]

shifted_SB_EBs = [EB.replace('.ms','_shift.ms') for EB in offset_SB_EBs]

#check by calculating offset again
for shifted_ms in shifted_SB_EBs:
    offset = alignment.find_offset(reference_ms=reference_for_SB_alignment,
                                   offset_ms=shifted_ms,npix=alignment_npix['SB'],
                                   cell_size=alignment_cell_size['SB'],
                                   spwid=continuum_spw_id)
    print(f'#offset for {shifted_ms}: ',offset)
#additional test: compute the offset of the EB SBs to each other:
for shifted_ms in shifted_SB_EBs[1:]:
    offset = alignment.find_offset(reference_ms=shifted_SB_EBs[0],
                                   offset_ms=shifted_ms,npix=alignment_npix['SB'],
                                   cell_size=alignment_cell_size['SB'],
                                   spwid=continuum_spw_id)
    print(f'#offset for {shifted_ms} to SB EB0: ',offset)
#offset for J1604_SB_EB0_initcont_selfcal_shift.ms:  [0.00043601 0.00033029]
#offset for J1604_SB_EB1_initcont_selfcal_shift.ms:  [1.04817347e-03 7.77905064e-05]
#offset for J1604_SB_EB1_initcont_selfcal_shift.ms to SB EB0:  [0.00372944 0.0006984 ]


# Merge shifted SB EBs for aligning ACA EBs
SB_concat_shifted = prefix+'_SB_concat_shifted.ms'
os.system('rm -rf '+SB_concat_shifted)
concat(vis=shifted_SB_EBs,concatvis=SB_concat_shifted,dirtol='0.1arcsec',
       copypointing=False)

# Align ACA EBs to concat shifted SB EBs
reference_for_ACA_alignment = SB_concat_shifted

offset_ACA_EBs = ['{}_{}_initcont_selfcal.ms'.format(prefix, params['name'])
                  for params in data_params_ACA.values()]

alignment.align_measurement_sets(reference_ms=reference_for_ACA_alignment,
                                 align_ms=offset_ACA_EBs,npix=alignment_npix['ACA'],
                                 cell_size=alignment_cell_size['ACA'],spwid=continuum_spw_id,
                                 plot_uv_grid=True,
                                 plot_file_template=alignment_plot_file_template)

#New coordinates for J1604_ACA_EB0_initcont_selfcal.ms
#requires a shift of [-0.34319,0.16626]

#New coordinates for J1604_ACA_EB1_initcont_selfcal.ms
#requires a shift of [0.031623,-0.04548]

#New coordinates for J1604_ACA_EB2_initcont_selfcal.ms
#requires a shift of [0.23812,0.015752]

#New coordinates for J1604_ACA_EB3_initcont_selfcal.ms
#requires a shift of [0.23261,-0.016534]


alignment_offsets['ACA_EB0'] = [-0.34319,0.16626]
alignment_offsets['ACA_EB1'] = [0.031623,-0.04548]
alignment_offsets['ACA_EB2'] = [0.23812,0.015752]
alignment_offsets['ACA_EB3'] = [0.23261,-0.016534]

shifted_ACA_EBs = [EB.replace('.ms','_shift.ms') for EB in offset_ACA_EBs]

#check by calculating offset again
for shifted_ms in shifted_ACA_EBs:
    offset = alignment.find_offset(reference_ms=reference_for_ACA_alignment,
                                   offset_ms=shifted_ms,npix=alignment_npix['ACA'],
                                   cell_size=alignment_cell_size['ACA'],
                                   spwid=continuum_spw_id)
    print(f'#offset for {shifted_ms}: ',offset)
#offset for J1604_ACA_EB0_initcont_selfcal_shift.ms:  [-0.01493868 -0.0023693 ]
#offset for J1604_ACA_EB1_initcont_selfcal_shift.ms:  [-0.00527742 -0.00187661]
#offset for J1604_ACA_EB2_initcont_selfcal_shift.ms:  [0.0174203  0.00579523]
#offset for J1604_ACA_EB3_initcont_selfcal_shift.ms:  [ 0.00950556 -0.00335022]

#additional test: compute the offset of the EBs to each other:
for shifted_ms in shifted_ACA_EBs[1:]:
    offset = alignment.find_offset(reference_ms=shifted_ACA_EBs[0],
                                   offset_ms=shifted_ms,npix=alignment_npix['ACA'],
                                   cell_size=alignment_cell_size['ACA'],
                                   spwid=continuum_spw_id)
    print(f'#offset for {shifted_ms} to ACA EB0: ',offset)
#offset for J1604_ACA_EB1_initcont_selfcal_shift.ms to ACA EB0:  [0.06167405 0.02444842]
#offset for J1604_ACA_EB2_initcont_selfcal_shift.ms to ACA EB0:  [0.03866009 0.00530104]
#offset for J1604_ACA_EB3_initcont_selfcal_shift.ms to ACA EB0:  [0.09466885 0.02195501]


#Remove the '_selfcal' part of the names to match the naming convention below.
for shifted_EB in shifted_LB_EBs+shifted_SB_EBs+shifted_ACA_EBs:
    os.system('mv {} {}'.format(shifted_EB, shifted_EB.replace('_selfcal', '')))


""" Check that the images are indeed aligned after the shift """
for EB_key,params in data_params_LB.items():
    imagename = prefix+'_'+params['name']+'_initcont_shift_image'
    tclean_wrapper(
                    vis=prefix+'_'+params['name']+'_initcont_shift.ms',
                    imagename=imagename,
                    deconvolver='multiscale',
                    scales=LB_scales,
                    mask=mask_TM,
                    threshold=LB_threshold[EB_key],
                    cellsize=LB_cellsize,
                    imsize=LB_imsize,
                    parallel=use_parallel)
    estimate_SNR(f'{imagename}.image',disk_mask=mask_TM,
                  noise_mask=noise_annulus_TM)
    rms = params['rms']
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['LB'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=alignment_folder)

## Compute intensity ratio between aligned images from LB EBs
default(immath)
for params in data_params_LB.values():
    ref_image = prefix+'_LB_EB2_initcont_shift_image.image'
    imagename = prefix+'_'+params['name']+'_initcont_shift_image'
    os.system('rm -rf '+imagename+'.ratio')
    immath(imagename=[ref_image,imagename+'.image'],mode='evalexpr',
           outfile=imagename+'.ratio',
           expr='iif(IM0 > 3*'+str(data_params_LB['LB2']['rms'])+', IM1/IM0, 0)')
    generate_image_png(f'{imagename}.ratio',
                       plot_sizes=[2*mask_semimajor,2*mask_semimajor],
                       color_scale_limits=[0.5,1.5],image_units='ratio',
                       save_folder=alignment_folder)

for EB_key,params in data_params_SB.items():
    imagename = prefix+'_'+params['name']+'_initcont_shift_image'
    tclean_wrapper(
                   vis=prefix+'_'+params['name']+'_initcont_shift.ms',
                   imagename=imagename,
                   deconvolver='multiscale',
                   scales=SB_scales,
                   mask=mask_TM,
                   threshold=SB_threshold[EB_key],
                   cellsize=SB_cellsize,
                   imsize=SB_imsize,
                   parallel=use_parallel)
    estimate_SNR(f'{imagename}.image',disk_mask=mask_TM,
                 noise_mask=noise_annulus_TM)
    rms = params['rms']
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['SB'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=alignment_folder)

## Compute intensity ratio between aligned images from SB EBs
default(immath)
for params in data_params_SB.values():
    ref_image = prefix+'_SB_EB1_initcont_shift_image.image'
    imagename = prefix+'_'+params['name']+'_initcont_shift_image'
    os.system('rm -rf '+imagename+'.ratio')
    immath(imagename=[ref_image,imagename+'.image'],mode='evalexpr',
           outfile=imagename+'.ratio',
           expr='iif(IM0 > 3*'+str(data_params_SB['SB1']['rms'])+', IM1/IM0, 0)'
           )
    generate_image_png(f'{imagename}.ratio',
                       plot_sizes=[2*mask_semimajor,2*mask_semimajor],
                       color_scale_limits=[0.5,1.5],image_units='ratio',
                       save_folder=alignment_folder)


for EB_key,params in data_params_ACA.items():
    imagename = prefix+'_'+params['name']+'_initcont_shift_image'
    tclean_wrapper(
                 vis=prefix+'_'+params['name']+'_initcont_shift.ms',
                 imagename=imagename,
                 deconvolver='hogbom',
                 mask=mask_ACA,
                 threshold=ACA_threshold[EB_key],
                 cellsize=ACA_cellsize,
                 imsize=ACA_imsize,
                 parallel=use_parallel,
                )
    estimate_SNR(f'{imagename}.image', disk_mask = mask_ACA, noise_mask = noise_annulus_ACA)
    rms = params['rms']
    generate_image_png(f'{imagename}.image',plot_sizes=image_png_plot_sizes['ACA'],
                       color_scale_limits=[-3*rms,10*rms],
                       save_folder=alignment_folder)

## Compute intensity ratio between aligned images from ACA EBs
default(immath)
for params in data_params_ACA.values():
    ref_image = prefix+'_ACA_EB1_initcont_shift_image.image'
    imagename = prefix+'_'+params['name']+'_initcont_shift_image'
    os.system('rm -rf '+imagename+'.ratio')
    immath(imagename=[ref_image,imagename+'.image'],mode='evalexpr',
           outfile=imagename+'.ratio',
           expr='iif(IM0 > 3*'+str(data_params_ACA['ACA1']['rms'])+', IM1/IM0, 0)'
           )
    generate_image_png(f'{imagename}.ratio',
                       plot_sizes=[2*mask_semimajor_ACA,2*mask_semimajor_ACA],
                       color_scale_limits=[0.5,1.5],image_units='ratio',
                       save_folder=alignment_folder)

#for ACA, we see a small shift in the ratio, so let's fit Gaussians as an alternative
#alignment procedure to check
#we fit to the non-aligned, self-caled images
for params in data_params_ACA.values():
    print('#'+params['name'])
    fit_gaussian(prefix+'_'+params['name']+'_initcont_selfcal_image.image',
                 region=mask_ACA)

#ACA_EB0
#Peak in J2000 coordinates: 16:04:21.60845, -021:30:28.884147
#Pixel coordinates of peak: x = 50.891 y = 50.346

#ACA_EB1
#Peak in J2000 coordinates: 16:04:21.63987, -021:30:29.109087
#Pixel coordinates of peak: x = 50.014 y = 49.896

#ACA_EB2
#Peak in J2000 coordinates: 16:04:21.65290, -021:30:29.062167
#Pixel coordinates of peak: x = 49.650 y = 49.990

#ACA_EB3
#Peak in J2000 coordinates: 16:04:21.66053, -021:30:29.040397
#Pixel coordinates of peak: x = 49.437 y = 50.033

#compare to alignment in uv plane (in arcsec):
#ACA cellsize 0.5arcsec
# alignment_offsets['ACA_EB0'] = [-0.34319,0.16626]
# alignment_offsets['ACA_EB1'] = [0.031623,-0.04548]
# alignment_offsets['ACA_EB2'] = [0.23812,0.015752]
# alignment_offsets['ACA_EB3'] = [0.23261,-0.016534]

#looks consistent

#to check, fit also Gaussians to the shifted images:
for params in data_params_ACA.values():
    print('#'+params['name'])
    fit_gaussian(prefix+'_'+params['name']+'_initcont_shift_image.image',
                 region=mask_ACA)
#ACA_EB0
#Pixel coordinates of peak: x = 50.252 y = 50.014
#ACA_EB1
#Pixel coordinates of peak: x = 50.121 y = 49.993
#ACA_EB2
#Pixel coordinates of peak: x = 50.179 y = 49.959
#ACA_EB3
#Pixel coordinates of peak: x = 49.933 y = 50.068

#Ok, only sub-pixel offsets


""" Now that everything is aligned, we inspect the flux calibration. """

for params in data_params.values():
    msfile = prefix+'_'+params['name']+'_initcont_shift.ms'
    export_MS(msfile) #export MS contents into Numpy save files


""" Plot deprojected visibility profiles for all data together """
list_npz_files = []
for baseline_key,n_EB in number_of_EBs.items():
    list_npz_files += [f'{prefix}_{baseline_key}_EB{i}_initcont_shift.vis.npz'
                       for i in range(n_EB)]

deprojected_vis_profiles_folder = get_figures_folderpath('6_deprojected_vis_profiles')
make_figures_folder(deprojected_vis_profiles_folder)

plot_deprojected(filelist=list_npz_files,
                 fluxscale=[1.]*(number_of_EBs['LB']+number_of_EBs['SB']+number_of_EBs['ACA']),
                 PA=PA,incl=incl,show_err=True,
                 plot_label=os.path.join(deprojected_vis_profiles_folder,
                                         prefix+'_flux_scale_EB_preselfcal.png'))


flux_comparison_folder = get_figures_folderpath('7_flux_comparisons')
make_figures_folder(flux_comparison_folder)

"""

SB has overlapping uv ranges with both ACA and LB, so
we select an SB EB as the reference for flux scaling.

In case this source does not have ACA data, simply ignore the ACA steps in the list below.
 
If all SB EBs suffer from decoherence and cannot be used, see below

We correct flux differences >4%, if phase noise looks reasonable

If you need to re-scale fluxes, use command:
rescale_flux(vis=prefix+'_LB_EB0_initcont_shift.ms', gencalparameter=[1.044])

The general procedure is as follows:
1) check flux scaling, and if flux differences are >4%, re-scale the fluxes unless
    there is clear de-coherence (e.g. seen as a systematic decrease of scaling with UV distance)
2) do not scale those EBs with phase decoherence. Proceed with self-cal following the steps below 
   to the point that those EBs are self calibrated
3) check flux scaling again
4) if no flux scaling has been applied in 1), and you now still see a flux offset, then
    apply the flux scaling determined in step 3) to the non-self caled EBs
    and repeat the self-cal

If all SB EBs suffer from phase decoherence and cannot be used as the reference
for flux scaling:
1) concat ACA data and self-cal them in phase
2) concat them to SB data and self-cal them in phase
3) check flux offsets
4) if there are flux offsets, go back to 1), but before re-starting the process apply
    the corrections to the non-self caled ACA and SB data, and re-do steps 1) - 3).
    For this you should add additional code (essentially copy/paste the code from the first
    iteration) that repeats steps 1-3, but saves all output with different filenames. Remember
    to use the right filenames when you continue the script after step 6
5) Check flux offsets of LB EBs to a correct SB EB
6) concat LB data to ACA+SB and continue with script

"""

flux_ref_EB = 'SB_EB1'

#if you had to choose an LB EB, then iterate over data_params_SBLB constructed like this:
# data_params_SBLB = data_params_LB.copy()
# data_params_SBLB.update(data_params_SB)
#in that case, the call to estimate_flux_scale is just for exploring purposes by looking at the
#figures. in particular, the derived flux scalings are not used anywhere. this is because
#we need an SB EB to derive flux scalings, because only SB has overlapping baselines
#with both LB and ACA

for params in data_params.values():
#for params in data_params_SBLB.values():
    estimate_flux_scale(reference=prefix+f'_{flux_ref_EB}_initcont_shift.vis.npz',
                        comparison=prefix+'_'+params['name']+'_initcont_shift.vis.npz',
                        incl=incl, PA=PA,ymax=2,
                        plot_label=os.path.join(flux_comparison_folder,
                                                'flux_comparison_with_offset_'+params['name']+f'_to_{flux_ref_EB}.png'),)

#The ratio of the fluxes of J1604_LB_EB0_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 1.04415
#The scaling factor for gencal is 1.022 for your comparison measurement
#The error on the weighted mean ratio is 1.020e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_LB_EB1_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 1.03798
#The scaling factor for gencal is 1.019 for your comparison measurement
#The error on the weighted mean ratio is 9.028e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_LB_EB2_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 1.06838
#The scaling factor for gencal is 1.034 for your comparison measurement
#The error on the weighted mean ratio is 8.937e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_SB_EB0_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 0.91846
#The scaling factor for gencal is 0.958 for your comparison measurement
#The error on the weighted mean ratio is 5.199e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_SB_EB1_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.698e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACA_EB0_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 0.93637
#The scaling factor for gencal is 0.968 for your comparison measurement
#The error on the weighted mean ratio is 4.347e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACA_EB1_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 1.00058
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.130e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACA_EB2_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 0.94252
#The scaling factor for gencal is 0.971 for your comparison measurement
#The error on the weighted mean ratio is 2.634e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACA_EB3_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 0.93929
#The scaling factor for gencal is 0.969 for your comparison measurement
#The error on the weighted mean ratio is 3.567e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor


#flux offsets larger than 4%, but there seems to be some decoherence,
#so let's proceed without scaling and see if selfcal can fix it


"""
Self-cal of ACA data only
"""
#for phase self-cal, we clean down to 6 sigma

ACA_selfcal_folder = get_figures_folderpath('8_selfcal_ACA_figures')
make_figures_folder(ACA_selfcal_folder)

""" Merge the SB executions back into a single MS """
ACA_cont_p0 = prefix+'_ACA_contp0'
os.system('rm -rf %s.ms*' % ACA_cont_p0)
concat(vis=[f'{prefix}_ACA_EB{i}_initcont_shift.ms' for i in range(number_of_EBs['ACA'])],
       concatvis=ACA_cont_p0+'.ms',dirtol='0.1arcsec',copypointing=False)

listobs(
    vis=ACA_cont_p0+'.ms',
    listfile=ACA_cont_p0+'.ms.txt',
    overwrite=True)

"""Define mask for ACA clean, using the new center from listobs"""
mask_ra = '16h04m21.6417s'
mask_dec = '-21.30.29.0583'
mask_ACA = f'ellipse[[{mask_ra},{mask_dec}], [{mask_semimajor_ACA:.3f}arcsec, {mask_semiminor_ACA:.3f}arcsec], {mask_pa:.1f}deg]'

noise_annulus_ACA = f"annulus[[{mask_ra}, {mask_dec}], ['11.arcsec', '18.arcsec']]"

""" Initial clean (down to 6 sigma)"""
tclean_wrapper(vis=ACA_cont_p0+'.ms', imagename = ACA_cont_p0, mask=mask_ACA,
               deconvolver='hogbom',threshold = f'{6*1.46}mJy', savemodel = 'modelcolumn',
               imsize=ACA_imsize,cellsize=ACA_cellsize, robust=0.5, interactive=False,
               parallel=use_parallel)
estimate_SNR(ACA_cont_p0+'.image', disk_mask = mask_ACA, noise_mask = noise_annulus_ACA)
#J1604_ACA_contp0.image
#Beam 4.550 arcsec x 3.512 arcsec (-70.42 deg)
#Flux inside disk mask: 178.52 mJy
#Peak intensity of source: 173.12 mJy/beam
#rms: 1.31e+00 mJy/beam
#Peak SNR: 132.44

rms_ACA = imstat(imagename = ACA_cont_p0+'.image', region = noise_annulus_ACA)['rms'][0]
generate_image_png(ACA_cont_p0+'.image',plot_sizes=image_png_plot_sizes['ACA'],
                   color_scale_limits=[-3*rms_ACA,10*rms_ACA],
                   save_folder=ACA_selfcal_folder,mask=ACA_cont_p0+'.mask',
                   noise_annulus=noise_annulus_ACA)


""" Self-calibration parameters """

""" Look for references antennas from weblog, and pick the first that are listed, overlapping with all EBs """
# ACA0: CM02, CM03, CM10
# ACA1: CM02, CM03, CM10
# ACA2: CM02, CM03, CM05
# ACA3: CM02, CM03, CM05
get_station_numbers(ACA_cont_p0+'.ms','CM02')
ACA_refant   = 'CM02@J502'

ACA_contspws = '0~15'
ACA_spw_mapping = [0,0,0,0,4,4,4,4,8,8,8,8,12,12,12,12]


""" First round of phase-only self-cal """
# Use scan-length interval to align SPWs as much as possible
ACA_p1 = prefix+'_ACA.p1'
os.system('rm -rf '+ACA_p1)
gaincal(vis=ACA_cont_p0+'.ms', caltable=ACA_p1, gaintype='G', spw=ACA_contspws,
        refant=ACA_refant, combine='scan', calmode='p', solint='inf', minsnr=3.,
        minblperant=3)


""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(ACA_p1,xaxis='time', yaxis='GainPhase')
""" Print calibration png file """
plotms(ACA_p1,xaxis='time', yaxis='GainPhase',overwrite=True,showgui=False,
       plotfile=os.path.join(ACA_selfcal_folder,prefix+'_ACA_gain_p1_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=ACA_cont_p0+'.ms', spw=ACA_contspws, gaintable=[ACA_p1],
         interp='linear', calwt=True, applymode='calonly')

""" Split off a corrected MS """
ACA_cont_p1 = prefix+'_ACA_contp1'
os.system('rm -rf %s.ms*' % ACA_cont_p1)
split(vis=ACA_cont_p0+'.ms', outputvis=ACA_cont_p1+'.ms', datacolumn='corrected')


""" Image the results; check the resulting map """
#again clean down to 6 sigma
tclean_wrapper(vis=ACA_cont_p1+'.ms', imagename = ACA_cont_p1, mask=mask_ACA,
               threshold = f'{6*1.2}mJy', savemodel = 'modelcolumn', imsize=ACA_imsize,
               cellsize=ACA_cellsize, robust=0.5, interactive=False,parallel=use_parallel)
estimate_SNR(ACA_cont_p1+'.image', disk_mask = mask_ACA, noise_mask = noise_annulus_ACA)
generate_image_png(ACA_cont_p1+'.image',plot_sizes=image_png_plot_sizes['ACA'],
                   color_scale_limits=[-3*rms_ACA,10*rms_ACA],
                   save_folder=ACA_selfcal_folder)
#J1604_ACA_contp1.image
#Beam 4.550 arcsec x 3.512 arcsec (-70.42 deg)
#Flux inside disk mask: 178.68 mJy
#Peak intensity of source: 173.32 mJy/beam
#rms: 1.27e+00 mJy/beam
#Peak SNR: 135.95

""" Second round of phase-only self-cal (ACA only) """
ACA_p2 = prefix+'_ACA.p2'
os.system('rm -rf '+ACA_p2)
gaincal(vis=ACA_cont_p1+'.ms', caltable=ACA_p2, gaintype='T', spw=ACA_contspws,
        refant=ACA_refant, combine='spw', calmode='p', solint='30s', minsnr=3.,
        minblperant=3)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(ACA_p2,xaxis='time', yaxis='GainPhase')
""" Print calibration png file """
plotms(ACA_p2,xaxis='time', yaxis='GainPhase',overwrite=True,showgui=False,
       plotfile=os.path.join(ACA_selfcal_folder,prefix+'_ACA_gain_p2_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=ACA_cont_p1+'.ms', spw=ACA_contspws, spwmap = ACA_spw_mapping,
         gaintable=[ACA_p2], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
ACA_cont_p2 = prefix+'_ACA_contp2'
os.system('rm -rf %s.ms*' % ACA_cont_p2)
split(vis=ACA_cont_p1+'.ms', outputvis=ACA_cont_p2+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=ACA_cont_p2+'.ms', imagename = ACA_cont_p2, mask=mask_ACA,
               threshold = '6mJy', savemodel = 'modelcolumn', imsize=ACA_imsize,
               cellsize=ACA_cellsize, robust=0.5, interactive=False,parallel=use_parallel)
estimate_SNR(ACA_cont_p2+'.image', disk_mask = mask_ACA, noise_mask = noise_annulus_ACA)
generate_image_png(ACA_cont_p2+'.image',plot_sizes=image_png_plot_sizes['ACA'],
                   color_scale_limits=[-3*rms_ACA,10*rms_ACA],
                   save_folder=ACA_selfcal_folder)
#J1604_ACA_contp2.image
#Beam 4.550 arcsec x 3.512 arcsec (-70.42 deg)
#Flux inside disk mask: 184.53 mJy
#Peak intensity of source: 183.09 mJy/beam
#rms: 9.86e-01 mJy/beam
#Peak SNR: 185.64

non_self_caled_ACA_vis = ACA_cont_p0
self_caled_ACA_visibilities = {'p1':ACA_cont_p1,
                               'p2':ACA_cont_p2}

#be sure to check if the following is correct
ACA_EBs = ('EB0','EB1','EB2','EB3')
ACA_EB_spws = ('0,1,2,3','4,5,6,7','8,9,10,11','12,13,14,15')

for self_cal_step,self_caled_vis in self_caled_ACA_visibilities.items():
    for EB_key,spw in zip(ACA_EBs,ACA_EB_spws):
        nametemplate = f'{prefix}_ACA_{EB_key}_{self_cal_step}_compare_amp_vs_time'
        visibilities = [self_caled_vis+'.ms',non_self_caled_ACA_vis+'.ms']
        #we plot the whole uv range because sources are unresolved for ACA
        plot_amp_vs_time_comparison(
                nametemplate=nametemplate,visibilities=visibilities,spw=spw,
                uvrange=uv_ranges['ACA'],output_folder=ACA_selfcal_folder)
#EB2 looks better after self-cal in these plots

all_ACA_visibilities = self_caled_ACA_visibilities.copy()
all_ACA_visibilities['p0'] = ACA_cont_p0

for self_cal_step,vis_name in all_ACA_visibilities.items():
    #split out EBs
    vis_ms = vis_name+'.ms'
    nametemplate = vis_ms.replace('.ms','_EB')
    split_all_obs(msfile=vis_ms,nametemplate=nametemplate)
    exported_ms = []
    for i in range(number_of_EBs['ACA']):
        EB_vis = f'{nametemplate}{i}.ms'
        export_MS(EB_vis)
        exported_ms.append(EB_vis.replace('.ms','.vis.npz'))
    for i,exp_ms in enumerate(exported_ms):
        png_filename = f'flux_comparison_ACA_{self_cal_step}_{flux_ref_EB}_to_ACA_EB{i}.png'
        plot_label = os.path.join(ACA_selfcal_folder,png_filename)
        assert 'SB' in flux_ref_EB, 'comparison to ACA is only possible with SB (or ACA itself)'
        estimate_flux_scale(reference=prefix+f'_{flux_ref_EB}_initcont_shift.vis.npz',
                            comparison=exp_ms,incl=incl,PA=PA,plot_label=plot_label)
    fluxscale = [1.,]*number_of_EBs['ACA']
    plot_label = os.path.join(ACA_selfcal_folder,
                              f'deprojected_vis_profiles_ACA_{self_cal_step}.png')
    plot_deprojected(filelist=exported_ms,fluxscale=fluxscale, PA=PA, incl=incl,
                     show_err=True,plot_label=plot_label)

#flux scale looks good now, except for the last data point of EB2


"""SELF-CAL ACA + SB data"""
#reminder: clean down to 6 sigma for phase self-cal

SB_selfcal_folder = get_figures_folderpath('9_selfcal_ACASB_figures')
make_figures_folder(SB_selfcal_folder)

""" Merge the ACA self-cal'ed ms with SB ms"""
SB_cont_p0 = prefix+'_ACASB_contp0'
os.system('rm -rf %s.ms*' % SB_cont_p0)

concat(vis=[ACA_cont_p2+'.ms']+[f'{prefix}_SB_EB{i}_initcont_shift.ms' for i
                                          in range(number_of_EBs['SB'])],
            concatvis=SB_cont_p0+'.ms', dirtol='0.1arcsec', copypointing=False)

listobs(
    vis=SB_cont_p0+'.ms',
    listfile=SB_cont_p0+'.ms.txt',
    overwrite=True,
)

"""Define new SB mask using new center (from listobs output) 16:04:21.662000 -21.30.28.39100"""
mask_ra = '16h04m21.6417s'
mask_dec = '-21.30.29.0583'

#there is an offset between the phase center and the center of the disk (probably
#proper motion was wrong), so I need to make the mask a little larger
mask_semimajor = 2.5 #semimajor axis of mask in arcsec
mask_semiminor = mask_semimajor*np.cos(incl/180.*np.pi) #semiminor axis of mask in arcsec
SB_mask= f'ellipse[[{mask_ra},{mask_dec}], [{mask_semimajor:.3f}arcsec, {mask_semiminor:.3f}arcsec], {mask_pa:.1f}deg]'

noise_annulus_SB = f"annulus[[{mask_ra}, {mask_dec}],['4.arcsec', '6.arcsec']]"

delete_tclean_output(SB_cont_p0)
tclean_wrapper(vis=SB_cont_p0+'.ms', imagename = SB_cont_p0, mask=SB_mask,
               threshold = f'{6*0.064}mJy', deconvolver='multiscale', scales=SB_scales,
               savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p0+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
#J1604_ACASB_contp0.image
#Beam 0.514 arcsec x 0.399 arcsec (77.93 deg)
#Flux inside disk mask: 192.87 mJy
#Peak intensity of source: 25.37 mJy/beam
#rms: 6.47e-02 mJy/beam
#Peak SNR: 391.91

rms_SB = imstat(imagename = SB_cont_p0+'.image', region = noise_annulus_SB)['rms'][0]
generate_image_png(SB_cont_p0+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_selfcal_folder,
                   mask=SB_cont_p0+'.mask',noise_annulus=noise_annulus_SB)


""" Look for references antennas from weblog, and pick the first that are listed, overlapping with all EBs """
""" Since we are combined ACA EBs to SB EBs, ref antennas for both ACA and SB are needed """
#EB0: DV08, DA45, DV05, DA57, DA50
#EB1: DA63, DA52, DA57, DV08, DV14,

""" Get station numbers """
get_station_numbers(SB_cont_p0+'.ms','DV08')
get_station_numbers(SB_cont_p0+'.ms','DA57')
#Observation ID 4: DV08@A036
#Observation ID 5: DV08@A036
#Observation ID 4: DA57@A001
#Observation ID 5: DA57@A001

SB_contspws = '0~23'
SB_refant   = f'DV08@A036, {ACA_refant}'

SB_spw_mapping = [0,0,0,0,4,4,4,4,8,8,8,8,12,12,12,12,16,16,16,16,20,20,20,20]

SB_p1 = prefix+'_ACASB.p1'
os.system('rm -rf '+SB_p1)
gaincal(vis=SB_cont_p0+'.ms', caltable=SB_p1, gaintype='G', spw=SB_contspws,
        refant=SB_refant, combine='scan,spw', calmode='p', solint='inf', minsnr=3.,
        minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(SB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_selfcal_folder,prefix+'_SB_gain_p1_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=SB_cont_p0+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping,
         gaintable=[SB_p1], interp='linearPD', calwt=True, applymode='calonly')

SB_cont_p1 = prefix+'_ACASB_contp1'
os.system('rm -rf %s.ms*' % SB_cont_p1)
split(vis=SB_cont_p0+'.ms', outputvis=SB_cont_p1+'.ms', datacolumn='corrected')

delete_tclean_output(SB_cont_p1)
tclean_wrapper(vis=SB_cont_p1+'.ms', imagename = SB_cont_p1, mask=SB_mask,
               threshold = f'{6*0.064}mJy', deconvolver='multiscale', scales=SB_scales,
               savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p1+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
#J1604_ACASB_contp1.image
#Beam 0.514 arcsec x 0.399 arcsec (77.93 deg)
#Flux inside disk mask: 192.97 mJy
#Peak intensity of source: 25.39 mJy/beam
#rms: 6.26e-02 mJy/beam
#Peak SNR: 405.35

generate_image_png(SB_cont_p1+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_selfcal_folder,
                   mask=SB_cont_p1+'.mask',noise_annulus=noise_annulus_SB)


SB_p2 = prefix+'_ACASB.p2'
os.system('rm -rf '+SB_p2)
gaincal(vis=SB_cont_p1+'.ms', caltable=SB_p2, gaintype='T', spw=SB_contspws,
        refant=SB_refant, combine='scan, spw', calmode='p', solint='360s',
        minsnr=3., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(SB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_selfcal_folder,prefix+'_SB_gain_p2_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=SB_cont_p1+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping,
         gaintable=[SB_p2], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p2 = prefix+'_ACASB_contp2'
os.system('rm -rf %s.ms*' % SB_cont_p2)
split(vis=SB_cont_p1+'.ms', outputvis=SB_cont_p2+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
delete_tclean_output(SB_cont_p2)
tclean_wrapper(vis=SB_cont_p2+'.ms', imagename = SB_cont_p2, mask=SB_mask,
               threshold = f'{6*0.06}mJy', deconvolver='multiscale', scales=SB_scales,
               savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p2+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
#J1604_ACASB_contp2.image
#Beam 0.514 arcsec x 0.399 arcsec (77.93 deg)
#Flux inside disk mask: 193.35 mJy
#Peak intensity of source: 25.51 mJy/beam
#rms: 5.75e-02 mJy/beam
#Peak SNR: 443.47

generate_image_png(SB_cont_p2+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_selfcal_folder,
                   mask=SB_cont_p2+'.mask',noise_annulus=noise_annulus_SB)


SB_p3 = prefix+'_ACASB.p3'
os.system('rm -rf '+SB_p3)
gaincal(vis=SB_cont_p2+'.ms', caltable=SB_p3, gaintype='T', spw=SB_contspws,
        refant=SB_refant, combine='spw', calmode='p', solint='120s', minsnr=3.,
        minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(SB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_selfcal_folder,prefix+'_SB_gain_p3_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=SB_cont_p2+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping,
         gaintable=[SB_p3], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p3 = prefix+'_ACASB_contp3'
os.system('rm -rf %s.ms*' % SB_cont_p3)
split(vis=SB_cont_p2+'.ms', outputvis=SB_cont_p3+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
delete_tclean_output(SB_cont_p3)
tclean_wrapper(vis=SB_cont_p3+'.ms', imagename = SB_cont_p3, mask=SB_mask,
               threshold = f'{6*0.058}mJy', deconvolver='multiscale', scales=SB_scales,
               savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p3+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
#J1604_ACASB_contp3.image
#Beam 0.514 arcsec x 0.399 arcsec (77.93 deg)
#Flux inside disk mask: 193.40 mJy
#Peak intensity of source: 25.54 mJy/beam
#rms: 5.64e-02 mJy/beam
#Peak SNR: 452.40

generate_image_png(SB_cont_p3+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_selfcal_folder,
                   mask=SB_cont_p3+'.mask',noise_annulus=noise_annulus_SB)


SB_p4 = prefix+'_ACASB.p4'
os.system('rm -rf '+SB_p4)
gaincal(vis=SB_cont_p3+'.ms', caltable=SB_p4, gaintype='T', spw=SB_contspws,
        refant=SB_refant, combine='spw', calmode='p', solint='60s', minsnr=3.,
        minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p4,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(SB_p4,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_selfcal_folder,prefix+'_SB_gain_p4_phase_vs_time.png'))

applycal(vis=SB_cont_p3+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping,
         gaintable=[SB_p4], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p4 = prefix+'_ACASB_contp4'
os.system('rm -rf %s.ms*' % SB_cont_p4)
split(vis=SB_cont_p3+'.ms', outputvis=SB_cont_p4+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=SB_cont_p4+'.ms', imagename = SB_cont_p4, mask=SB_mask,
               threshold = f'{6*0.057}mJy', deconvolver='multiscale', scales=SB_scales,
               savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p4+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
#J1604_ACASB_contp4.image
#Beam 0.514 arcsec x 0.399 arcsec (77.93 deg)
#Flux inside disk mask: 193.49 mJy
#Peak intensity of source: 25.60 mJy/beam
#rms: 5.57e-02 mJy/beam
#Peak SNR: 459.37

generate_image_png(SB_cont_p4+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_selfcal_folder,
                   mask=SB_cont_p4+'.mask',noise_annulus=noise_annulus_SB)


SB_p5 = prefix+'_ACASB.p5'
os.system('rm -rf '+SB_p5)
gaincal(vis=SB_cont_p4+'.ms', caltable=SB_p5, gaintype='T', spw=SB_contspws,
        refant=SB_refant, combine='spw', calmode='p', solint='20s', minsnr=3.,
        minblperant=4)
#quite some flagging (~10%?)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p5,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(SB_p5,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_selfcal_folder,prefix+'_SB_gain_p5_phase_vs_time.png'))

applycal(vis=SB_cont_p4+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping,
         gaintable=[SB_p5], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p5 = prefix+'_ACASB_contp5'
os.system('rm -rf %s.ms*' % SB_cont_p5)
split(vis=SB_cont_p4+'.ms', outputvis=SB_cont_p5+'.ms', datacolumn='corrected')


""" Image the results; check the resulting map """
delete_tclean_output(SB_cont_p5)
tclean_wrapper(vis=SB_cont_p5+'.ms', imagename = SB_cont_p5, mask=SB_mask,
               threshold = f'{6*0.057}mJy', deconvolver='multiscale', scales=SB_scales,
               savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p5+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
#J1604_ACASB_contp5.image
#Beam 0.514 arcsec x 0.399 arcsec (77.93 deg)
#Flux inside disk mask: 193.72 mJy
#Peak intensity of source: 25.68 mJy/beam
#rms: 5.67e-02 mJy/beam
#Peak SNR: 452.68

#the peak SNR decreased, but the gain solution showed some slope with time, so I
#decided to keep it

generate_image_png(SB_cont_p5+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_selfcal_folder,
                   mask=SB_cont_p5+'.mask',noise_annulus=noise_annulus_SB)


#plot amp vs time for a narrow uv range
non_self_caled_SB_vis = SB_cont_p0
self_caled_SB_visibilities = {'p1':SB_cont_p1,
                              'p2':SB_cont_p2,
                              'p3':SB_cont_p3,
                              'p4':SB_cont_p4,
                              'p5':SB_cont_p5}

SB_EBs = ('EB0','EB1')
SB_EB_spws = ('16,17,18,19','20,21,22,23') #fill in spws for each EB

for self_cal_step,self_caled_vis in self_caled_SB_visibilities.items():
    for EB_key,spw in zip(SB_EBs,SB_EB_spws):
        nametemplate = f'{prefix}_SB_{EB_key}_{self_cal_step}_compare_amp_vs_time'
        visibilities = [self_caled_vis+'.ms',non_self_caled_SB_vis+'.ms']
        plot_amp_vs_time_comparison(
                nametemplate=nametemplate,visibilities=visibilities,spw=spw,
                uvrange=uv_ranges['SB'],output_folder=SB_selfcal_folder)
#I don't really see a lot of change in thsese plots


all_SB_visibilities = self_caled_SB_visibilities.copy()
all_SB_visibilities['p0'] = SB_cont_p0

"""
if SB suffers from decoherence, then take an LB EB as flux reference; modify the code
below accordingly

If you haven't re-scaled the fluxes of LB EBs because all SB EBs had high decoherence,
check flux offsets of LB EBs here and correct them, if needed

"""

for self_cal_step,vis_name in all_SB_visibilities.items():
    #split out SB EBs
    vis_ms = vis_name+'.ms'
    nametemplate = vis_ms.replace('.ms','_EB')
    split_all_obs(msfile=vis_ms,nametemplate=nametemplate)
    exported_ms = []
    #we only consider SB, not ACA
    for i in range(number_of_EBs['ACA'],number_of_EBs['SB']+number_of_EBs['ACA']):
        EB_vis = f'{nametemplate}{i}.ms'
        export_MS(EB_vis) #export MS contents into Numpy save files
        exported_ms.append(EB_vis.replace('.ms','.vis.npz'))
    for i,exp_ms in zip(range(number_of_EBs['ACA'],number_of_EBs['SB']+number_of_EBs['ACA']),
                        exported_ms):
        png_filename = f'flux_comparison_ACASB_EB{i}_{self_cal_step}_to_{flux_ref_EB}.png'
        plot_label = os.path.join(SB_selfcal_folder,png_filename)
        estimate_flux_scale(reference=f'{prefix}_{flux_ref_EB}_initcont_shift.vis.npz',
                            comparison=exp_ms,incl=incl,PA=PA,plot_label=plot_label)
    fluxscale = [1.,]*number_of_EBs['SB']
    plot_label = os.path.join(SB_selfcal_folder,
                              f'deprojected_vis_profiles_SB_{self_cal_step}.png')
    plot_deprojected(filelist=exported_ms,fluxscale=fluxscale, PA=PA, incl=incl,
                     show_err=True,plot_label=plot_label)

#Measurement set exported to J1604_ACASB_contp0_EB5.vis.npz
#The ratio of the fluxes of J1604_ACASB_contp0_EB4.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 0.91846
#The scaling factor for gencal is 0.958 for your comparison measurement
#The error on the weighted mean ratio is 5.199e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASB_contp0_EB5.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.698e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#still large offset between the two EBs


#let's compare the self-caled ref SB with the non-self-caled LB:
SB_selfcaled_reference = f'{prefix}_ACASB_contp5_EB5.vis.npz'
for params in data_params_LB.values():
    estimate_flux_scale(reference=SB_selfcaled_reference,
                        comparison=prefix+'_'+params['name']+'_initcont_shift.vis.npz',
                        incl=incl, PA=PA,
                        plot_label=os.path.join(SB_selfcal_folder,
                                                'flux_comparison_'+params['name']+f'_to_{SB_selfcaled_reference}.png'))
#The ratio of the fluxes of J1604_LB_EB0_initcont_shift.vis.npz to
#J1604_ACASB_contp5_EB5.vis.npz is 1.03509

#The ratio of the fluxes of J1604_LB_EB1_initcont_shift.vis.npz to
#J1604_ACASB_contp5_EB5.vis.npz is 1.03046

#The ratio of the fluxes of J1604_LB_EB2_initcont_shift.vis.npz to
#J1604_ACASB_contp5_EB5.vis.npz is 1.06066

#still strong gradient with uv dist

#compare to what we had before self-cal:
    
#The ratio of the fluxes of J1604_LB_EB0_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 1.04415

#The ratio of the fluxes of J1604_LB_EB1_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 1.03798

#The ratio of the fluxes of J1604_LB_EB2_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 1.06838


#pretty much the same as before self-cal... let's see if LB self-cal can fix it...


"""SELF-CAL COMBINED DATA"""
LB_selfcal_folder = get_figures_folderpath('10_selfcal_ACASBLB_figures')
make_figures_folder(LB_selfcal_folder)

""" Merge the SB self-cal'ed ms with LB ms"""
LB_cont_p0 = prefix+'_ACASBLB_contp0'
os.system('rm -rf %s.ms*' % LB_cont_p0)

concat(vis=[SB_cont_p5+'.ms']+[f'{prefix}_LB_EB{i}_initcont_shift.ms' for i in
                               range(number_of_EBs['LB'])],
            concatvis=LB_cont_p0+'.ms', dirtol='0.1arcsec', copypointing=False)

listobs(
    vis=LB_cont_p0+'.ms',
    listfile=LB_cont_p0+'.ms.txt',
    overwrite=True,
)

#new mask based on listobs output
mask_ra = '16h04m21.6417s'
mask_dec = '-21.30.29.0583'

LB_mask = f'ellipse[[{mask_ra},{mask_dec}], [{mask_semimajor:.3f}arcsec, {mask_semiminor:.3f}arcsec], {mask_pa:.1f}deg]'
noise_annulus_LB = f"annulus[[{mask_ra}, {mask_dec}],['4.arcsec', '6.arcsec']]"

""" clean down to ~6 sigma"""
delete_tclean_output(LB_cont_p0)
tclean_wrapper(vis=LB_cont_p0+'.ms', imagename = LB_cont_p0, mask=LB_mask,
               threshold = f'{6*0.04}mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p0+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
#J1604_ACASBLB_contp0.image
#Beam 0.159 arcsec x 0.134 arcsec (-77.75 deg)
#Flux inside disk mask: 200.06 mJy
#Peak intensity of source: 5.60 mJy/beam
#rms: 3.96e-02 mJy/beam
#Peak SNR: 141.65

rms_LB = imstat(imagename = LB_cont_p0+'.image', region = noise_annulus_LB)['rms'][0]
generate_image_png(LB_cont_p0+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],save_folder=LB_selfcal_folder,
                   mask=LB_cont_p0+'.mask',noise_annulus=noise_annulus_LB)


""" Self-calibration parameters """

""" Look for references antennas from weblog, and pick the first that are listed,
overlapping with all EBs """
""" Since we are combined LB EBs to SB+ACA EBs, ref antennas for LB, SB and ACA are
needed """
#EB0: DV02, DV04, DV03, DV21, DV01, DA62, DV25, DA58
#EB1: DV06, DV03, DV02, DV04, DV01, DA58, DV21, DA55
#EB2: DV04, DV25, DA58, DV06, DV21, DV01, DA42, DV02,

#LB refants: DV02, DV01, DV04
#for SB, we used DV08@A036

for ant in ('DV02','DV01','DV04','DV08'):
    get_station_numbers(LB_cont_p0+'.ms',ant)
#Observation ID 5: DV02@A022
#Observation ID 6: DV02@A022
#Observation ID 7: DV02@A022
#Observation ID 8: DV02@A022

#Observation ID 4: DV01@A033
#Observation ID 5: DV01@A033
#Observation ID 6: DV01@A033
#Observation ID 7: DV01@A033
#Observation ID 8: DV01@A033

#Observation ID 6: DV04@A007
#Observation ID 7: DV04@A007
#Observation ID 8: DV04@A007

#Observation ID 4: DV08@A036
#Observation ID 5: DV08@A036
#Observation ID 6: DV08@A111
#Observation ID 7: DV08@A111
#Observation ID 8: DV08@A111

#SB refant DV08 has different pad number for LB; thus, we list it first in the list
#CASA will then use the LB ref ants, since it cannot find the DV08@A036

LB_refant = f'{SB_refant}, DV04@A007, DV02@A022'

LB_contspws = '0~35'

LB_spw_mapping = [0,0,0,0,4,4,4,4,8,8,8,8,12,12,12,12,16,16,16,16,20,20,20,20,
                  24,24,24,24,28,28,28,28,32,32,32,32]

LB_p1 = prefix+'_ACASBLB.p1'
os.system('rm -rf '+LB_p1)
#try gaintype='G', and if there are many flagged solutions, change it to 'T'
gaincal(vis=LB_cont_p0+'.ms', caltable=LB_p1, gaintype='G', spw=LB_contspws,
        refant=LB_refant, combine='scan,spw', calmode='p', solint='inf', minsnr=2.,
        minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(LB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_p1_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p0+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_p1], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p1 = prefix+'_ACASBLB_contp1'
os.system('rm -rf %s.ms*' % LB_cont_p1)
split(vis=LB_cont_p0+'.ms', outputvis=LB_cont_p1+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
delete_tclean_output(LB_cont_p1)
tclean_wrapper(vis=LB_cont_p1+'.ms', imagename = LB_cont_p1, mask=LB_mask,
               threshold = f'{6*0.039}mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p1+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
#J1604_ACASBLB_contp1.image
#Beam 0.159 arcsec x 0.134 arcsec (-77.75 deg)
#Flux inside disk mask: 200.47 mJy
#Peak intensity of source: 5.64 mJy/beam
#rms: 3.91e-02 mJy/beam
#Peak SNR: 144.37

generate_image_png(LB_cont_p1+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],save_folder=LB_selfcal_folder,
                   mask=LB_cont_p1+'.mask',noise_annulus=noise_annulus_LB)


""" Second round of phase-only self-cal (LB only) """
LB_p2 = prefix+'_ACASBLB.p2'
os.system('rm -rf '+LB_p2)
gaincal(vis=LB_cont_p1+'.ms', caltable=LB_p2, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw,scan', calmode='p', solint='360s', minsnr=2.,
        minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(LB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_p2_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p1+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_p2], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p2 = prefix+'_ACASBLB_contp2'
os.system('rm -rf %s.ms*' % LB_cont_p2)
split(vis=LB_cont_p1+'.ms', outputvis=LB_cont_p2+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
delete_tclean_output(LB_cont_p2)
tclean_wrapper(vis=LB_cont_p2+'.ms', imagename = LB_cont_p2, mask=LB_mask,
               threshold = f'{6*0.032}mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p2+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
#J1604_ACASBLB_contp2.image
#Beam 0.159 arcsec x 0.134 arcsec (-77.75 deg)
#Flux inside disk mask: 199.96 mJy
#Peak intensity of source: 5.85 mJy/beam
#rms: 3.09e-02 mJy/beam
#Peak SNR: 189.12


generate_image_png(LB_cont_p2+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],save_folder=LB_selfcal_folder,
                   mask=LB_cont_p2+'.mask',noise_annulus=noise_annulus_LB)

""" Third round of phase-only self-cal (LB only) """
"""
Check scan length to decide whether to combine scans. If scans are 2 min,
do not combine them. If they are shorter, combine scans here
"""
#LB scan length is 2-3 minutes, so we do not combine scanes
LB_p3 = prefix+'_ACASBLB.p3'
os.system('rm -rf '+LB_p3)
gaincal(vis=LB_cont_p2+'.ms', caltable=LB_p3, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw', calmode='p', solint='120s', minsnr=2.,
        minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(LB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_p3_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p2+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_p3], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p3 = prefix+'_ACASBLB_contp3'
os.system('rm -rf %s.ms*' % LB_cont_p3)
split(vis=LB_cont_p2+'.ms', outputvis=LB_cont_p3+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=LB_cont_p3+'.ms', imagename = LB_cont_p3, mask=LB_mask,
               threshold = f'{6*0.031}mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p3+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
#J1604_ACASBLB_contp3.image
#Beam 0.159 arcsec x 0.134 arcsec (-77.75 deg)
#Flux inside disk mask: 199.93 mJy
#Peak intensity of source: 5.92 mJy/beam
#rms: 3.04e-02 mJy/beam
#Peak SNR: 194.37


generate_image_png(LB_cont_p3+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],save_folder=LB_selfcal_folder,
                   mask=LB_cont_p3+'.mask',noise_annulus=noise_annulus_LB)


""" Clean down to 1 sigma for amplitude self-cal"""

tclean_wrapper(vis=LB_cont_p3+'.ms', imagename = LB_cont_p3, mask=LB_mask,
               threshold = '0.031mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p3+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
#J1604_ACASBLB_contp3.image
#Beam 0.159 arcsec x 0.134 arcsec (-77.75 deg)
#Flux inside disk mask: 196.28 mJy
#Peak intensity of source: 6.00 mJy/beam
#rms: 2.83e-02 mJy/beam
#Peak SNR: 211.87


""" Amplitude self-cal"""
LB_ap0 = prefix+'_ACASBLB.ap0'
os.system('rm -rf '+LB_ap0)
gaincal(vis=LB_cont_p3+'.ms', caltable=LB_ap0, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw, scan', calmode='ap', solint='inf', minsnr=5.0,
        minblperant=4, solnorm=False)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_ap0,xaxis='time', yaxis='GainPhase',iteraxis='spw')
plotms(LB_ap0,xaxis='time', yaxis='GainAmp',iteraxis='spw')

""" Print calibration png file """
plotms(LB_ap0,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_ap0_phase_vs_time.png'))
plotms(LB_ap0,xaxis='time', yaxis='GainAmp',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_ap0_amp_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p3+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_ap0], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_ap0 = prefix+'_ACASBLB_contap0'
os.system('rm -rf %s.ms*' % LB_cont_ap0)
split(vis=LB_cont_p3+'.ms', outputvis=LB_cont_ap0+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
#again clean down to 1 sigma
delete_tclean_output(LB_cont_ap0)
tclean_wrapper(vis=LB_cont_ap0+'.ms', imagename = LB_cont_ap0, mask=LB_mask,
               threshold = '0.028mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_ap0+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
#J1604_ACASBLB_contap0.image
#Beam 0.150 arcsec x 0.124 arcsec (-80.26 deg)
#Flux inside disk mask: 196.55 mJy
#Peak intensity of source: 5.43 mJy/beam
#rms: 2.57e-02 mJy/beam
#Peak SNR: 211.59


generate_image_png(LB_cont_ap0+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],save_folder=LB_selfcal_folder,
                   mask=LB_cont_ap0+'.mask',noise_annulus=noise_annulus_LB)

""" Try ampl self-cal on with shorter sol int (for reference, scan length is 2-3 min)"""
LB_ap1 = prefix+'_ACASBLB.ap1'
os.system('rm -rf '+LB_ap1)
gaincal(vis=LB_cont_ap0+'.ms', caltable=LB_ap1, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw, scan', calmode='ap', solint='360s', minsnr=5.0,
        minblperant=4, solnorm=False)
#some flagging, but no excessive

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_ap1,xaxis='time', yaxis='GainPhase',iteraxis='spw')
plotms(LB_ap1,xaxis='time', yaxis='GainAmp',iteraxis='spw')
#quite some amps below 0.8 and above 1.2, manually flagged

""" Print calibration png file """
plotms(LB_ap1,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_ap1_phase_vs_time.png'))
plotms(LB_ap1,xaxis='time', yaxis='GainAmp',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_selfcal_folder,prefix+'_LB_gain_ap1_amp_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_ap0+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_ap1], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_ap1 = prefix+'_ACASBLB_contap1'
os.system('rm -rf %s.ms*' % LB_cont_ap1)
split(vis=LB_cont_ap0+'.ms', outputvis=LB_cont_ap1+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=LB_cont_ap1+'.ms', imagename = LB_cont_ap1, mask=LB_mask,
               threshold = '0.028mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_ap1+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_ap1+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],save_folder=LB_selfcal_folder,
                   mask=LB_cont_ap1+'.mask',noise_annulus=noise_annulus_LB)
#J1604_ACASBLB_contap1.image
#Beam 0.150 arcsec x 0.121 arcsec (-79.83 deg)
#Flux inside disk mask: 196.91 mJy
#Peak intensity of source: 5.33 mJy/beam
#rms: 2.50e-02 mJy/beam
#Peak SNR: 212.65


self_caled_LB_visibilities = {'p1':LB_cont_p1,
                              'p2':LB_cont_p2,
                              'p3':LB_cont_p3,
                              'ap0':LB_cont_ap0,
                              'ap1':LB_cont_ap1}

for vis in self_caled_LB_visibilities.values(): 
    listobs(vis=vis+'.ms',listfile=vis+'ms.txt',overwrite=True)


LB_EBs = ('EB0','EB1','EB2')
LB_EB_spws = ('24,25,26,27','28,29,30,31','32,33,34,35') #fill out by referring to listobs output

for self_cal_step,self_caled_vis in self_caled_LB_visibilities.items():
    for EB_key,spw in zip(LB_EBs,LB_EB_spws):
        nametemplate = f'{prefix}_LB_{EB_key}_{self_cal_step}_compare_amp_vs_time'
        visibilities = [self_caled_vis+'.ms',LB_cont_p0+'.ms']
        #we plot the whole uv range because sources are unresolved for ACA
        plot_amp_vs_time_comparison(
                nametemplate=nametemplate,visibilities=visibilities,spw=spw,
                uvrange=uv_ranges['LB'],output_folder=LB_selfcal_folder)


#flux_comparison_ref_EB is set to the EB of the combined ACASBLB data that corresponds
#to flux_ref_EB
#However, if flux_ref_EB is not an SB EB, you should set flux_comparison_ref_EB to
#an SB EB, since only SB has overlapping baselines with both ACA and LB
#at this point in the script, SB should be correctly scaled and decoherence removed,
#so it should be ok to use SB as a reference
flux_comparison_ref_EB = 5
total_number_of_EBs = number_of_EBs['ACA']+number_of_EBs['SB']+number_of_EBs['LB']

for self_cal_step,vis in self_caled_LB_visibilities.items():
    nametemplate = f'{prefix}_ACASBLB_cont{self_cal_step}_EB'
    split_all_obs(msfile=vis+'.ms',nametemplate=nametemplate)
    for i in range(total_number_of_EBs):
        export_MS(f'{nametemplate}{i}.ms')
    reference = f'{nametemplate}{flux_comparison_ref_EB}.vis.npz'
    for i in range(total_number_of_EBs):
        output = f'flux_comparison_EB{i}_to_EB{flux_comparison_ref_EB}'\
                       +f'_ACASBLB_{self_cal_step}.png'
        plot_label = os.path.join(LB_selfcal_folder,output)
        estimate_flux_scale(reference=reference,
                            comparison=f'{nametemplate}{i}.vis.npz',
                            incl=incl, PA=PA,#uvbins = np.arange(40.,300.,20.),
                            plot_label=plot_label)
    filelist = [f'{nametemplate}{i}.vis.npz' for i in range(total_number_of_EBs)]
    fluxscale = [1.,]*total_number_of_EBs
    plot_deprojected(filelist=filelist,fluxscale=fluxscale, PA=PA, incl=incl,
                      show_err=True,
                      plot_label=os.path.join(LB_selfcal_folder,
                                              f'deprojected_vis_profiles_ACASBLB_{self_cal_step}.png'))

#The ratio of the fluxes of J1604_ACASBLB_contap1_EB0.vis.npz to
#J1604_ACASBLB_contap1_EB5.vis.npz is 0.98007
#The scaling factor for gencal is 0.990 for your comparison measurement
#The error on the weighted mean ratio is 4.272e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contap1_EB1.vis.npz to
#J1604_ACASBLB_contap1_EB5.vis.npz is 1.00108
#The scaling factor for gencal is 1.001 for your comparison measurement
#The error on the weighted mean ratio is 4.002e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contap1_EB2.vis.npz to
#J1604_ACASBLB_contap1_EB5.vis.npz is 1.00498
#The scaling factor for gencal is 1.002 for your comparison measurement
#The error on the weighted mean ratio is 2.590e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contap1_EB3.vis.npz to
#J1604_ACASBLB_contap1_EB5.vis.npz is 0.98968
#The scaling factor for gencal is 0.995 for your comparison measurement
#The error on the weighted mean ratio is 3.550e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contap1_EB4.vis.npz to
#J1604_ACASBLB_contap1_EB5.vis.npz is 0.99911
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 5.591e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contap1_EB5.vis.npz to
#J1604_ACASBLB_contap1_EB5.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.675e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contap1_EB6.vis.npz to
#J1604_ACASBLB_contap1_EB5.vis.npz is 0.99468
#The scaling factor for gencal is 0.997 for your comparison measurement
#The error on the weighted mean ratio is 9.509e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contap1_EB7.vis.npz to
#J1604_ACASBLB_contap1_EB5.vis.npz is 0.99902
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 8.619e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contap1_EB8.vis.npz to
#J1604_ACASBLB_contap1_EB5.vis.npz is 0.99864
#The scaling factor for gencal is 0.999 for your comparison measurement
#The error on the weighted mean ratio is 8.302e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#global flux ratios seem fixed by amp self-cal
#for LB EB0 we can see that the self-cal slighly improves the decoherence, but
#overall there seems still a trend of decreasing LB/SB flux with uvdist that is not
#fixed by self-cal

#However, after phase-only self-cal, there are still significant offsets:
    
#The ratio of the fluxes of J1604_ACASBLB_contp3_EB0.vis.npz to
#J1604_ACASBLB_contp3_EB5.vis.npz is 0.99181
#The scaling factor for gencal is 0.996 for your comparison measurement
#The error on the weighted mean ratio is 4.343e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contp3_EB1.vis.npz to
#J1604_ACASBLB_contp3_EB5.vis.npz is 1.02860
#The scaling factor for gencal is 1.014 for your comparison measurement
#The error on the weighted mean ratio is 4.124e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contp3_EB2.vis.npz to
#J1604_ACASBLB_contp3_EB5.vis.npz is 1.02096
#The scaling factor for gencal is 1.010 for your comparison measurement
#The error on the weighted mean ratio is 2.637e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contp3_EB3.vis.npz to
#J1604_ACASBLB_contp3_EB5.vis.npz is 0.99068
#The scaling factor for gencal is 0.995 for your comparison measurement
#The error on the weighted mean ratio is 3.564e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contp3_EB4.vis.npz to
#J1604_ACASBLB_contp3_EB5.vis.npz is 0.92639
#The scaling factor for gencal is 0.962 for your comparison measurement
#The error on the weighted mean ratio is 5.189e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contp3_EB5.vis.npz to
#J1604_ACASBLB_contp3_EB5.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.675e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contp3_EB6.vis.npz to
#J1604_ACASBLB_contp3_EB5.vis.npz is 1.06587
#The scaling factor for gencal is 1.032 for your comparison measurement
#The error on the weighted mean ratio is 1.019e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contp3_EB7.vis.npz to
#J1604_ACASBLB_contp3_EB5.vis.npz is 1.03770
#The scaling factor for gencal is 1.019 for your comparison measurement
#The error on the weighted mean ratio is 8.961e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_ACASBLB_contp3_EB8.vis.npz to
#J1604_ACASBLB_contp3_EB5.vis.npz is 1.06546
#The scaling factor for gencal is 1.032 for your comparison measurement
#The error on the weighted mean ratio is 8.861e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#Therefore we apply the scaling ot the non-self-caled EBs and redo the selfcal:

rescale_flux(vis=prefix+'_SB_EB0_initcont_shift.ms', gencalparameter=[0.962])
rescale_flux(vis=prefix+'_LB_EB0_initcont_shift.ms', gencalparameter=[1.032])
rescale_flux(vis=prefix+'_LB_EB1_initcont_shift.ms', gencalparameter=[1.032])


##################### self-cal of flux-scaled data ################################
#since ACA was not scaled, we can start directly with SB
SB_scaled_selfcal_folder = get_figures_folderpath('11_scaled_selfcal_ACASB_figures')
make_figures_folder(SB_scaled_selfcal_folder)

""" Merge the ACA self-cal'ed ms with SB ms"""
SB_cont_p0 = prefix+'_scaled_ACASB_contp0'
os.system('rm -rf %s.ms*' % SB_cont_p0)

concat(vis=[ACA_cont_p2+'.ms']+[f'{prefix}_SB_EB0_initcont_shift_rescaled.ms',
                                f'{prefix}_SB_EB1_initcont_shift.ms'],
            concatvis=SB_cont_p0+'.ms', dirtol='0.1arcsec', copypointing=False)

listobs(
    vis=SB_cont_p0+'.ms',
    listfile=SB_cont_p0+'.ms.txt',
    overwrite=True,
)


tclean_wrapper(vis=SB_cont_p0+'.ms', imagename = SB_cont_p0, mask=SB_mask,
               threshold = f'{6*0.064}mJy', deconvolver='multiscale', scales=SB_scales,
               savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p0+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
#J1604_scaled_ACASB_contp0.image
#Beam 0.516 arcsec x 0.401 arcsec (77.89 deg)
#Flux inside disk mask: 197.37 mJy
#Peak intensity of source: 26.22 mJy/beam
#rms: 6.24e-02 mJy/beam
#Peak SNR: 420.49


rms_SB = imstat(imagename = SB_cont_p0+'.image', region = noise_annulus_SB)['rms'][0]
generate_image_png(SB_cont_p0+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],save_folder=SB_scaled_selfcal_folder,
                   mask=SB_cont_p0+'.mask',noise_annulus=noise_annulus_SB)


SB_p1 = prefix+'_scaled_ACASB.p1'
os.system('rm -rf '+SB_p1)
gaincal(vis=SB_cont_p0+'.ms', caltable=SB_p1, gaintype='G', spw=SB_contspws,
        refant=SB_refant, combine='scan,spw', calmode='p', solint='inf', minsnr=3.,
        minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(SB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_scaled_selfcal_folder,prefix+'_SB_gain_p1_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=SB_cont_p0+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping,
         gaintable=[SB_p1], interp='linearPD', calwt=True, applymode='calonly')

SB_cont_p1 = prefix+'_scaled_ACASB_contp1'
os.system('rm -rf %s.ms*' % SB_cont_p1)
split(vis=SB_cont_p0+'.ms', outputvis=SB_cont_p1+'.ms', datacolumn='corrected')

delete_tclean_output(SB_cont_p1)
tclean_wrapper(vis=SB_cont_p1+'.ms', imagename = SB_cont_p1, mask=SB_mask,
               threshold = f'{6*0.06}mJy', deconvolver='multiscale', scales=SB_scales,
               savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p1+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
#J1604_scaled_ACASB_contp1.image
#Beam 0.516 arcsec x 0.401 arcsec (77.89 deg)
#Flux inside disk mask: 197.54 mJy
#Peak intensity of source: 26.22 mJy/beam
#rms: 6.00e-02 mJy/beam
#Peak SNR: 436.76


generate_image_png(SB_cont_p1+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],
                   save_folder=SB_scaled_selfcal_folder,
                   mask=SB_cont_p1+'.mask',noise_annulus=noise_annulus_SB)


SB_p2 = prefix+'_scaled_ACASB.p2'
os.system('rm -rf '+SB_p2)
gaincal(vis=SB_cont_p1+'.ms', caltable=SB_p2, gaintype='T', spw=SB_contspws,
        refant=SB_refant, combine='scan, spw', calmode='p', solint='360s',
        minsnr=3., minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(SB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_scaled_selfcal_folder,prefix+'_SB_gain_p2_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=SB_cont_p1+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping,
         gaintable=[SB_p2], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p2 = prefix+'_scaled_ACASB_contp2'
os.system('rm -rf %s.ms*' % SB_cont_p2)
split(vis=SB_cont_p1+'.ms', outputvis=SB_cont_p2+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
delete_tclean_output(SB_cont_p2)
tclean_wrapper(vis=SB_cont_p2+'.ms', imagename = SB_cont_p2, mask=SB_mask,
               threshold = f'{6*0.057}mJy', deconvolver='multiscale', scales=SB_scales,
               savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p2+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
#J1604_scaled_ACASB_contp2.image
#Beam 0.516 arcsec x 0.401 arcsec (77.89 deg)
#Flux inside disk mask: 197.88 mJy
#Peak intensity of source: 26.35 mJy/beam
#rms: 5.50e-02 mJy/beam
#Peak SNR: 479.42


generate_image_png(SB_cont_p2+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],
                   save_folder=SB_scaled_selfcal_folder,
                   mask=SB_cont_p2+'.mask',noise_annulus=noise_annulus_SB)


SB_p3 = prefix+'_scaled_ACASB.p3'
os.system('rm -rf '+SB_p3)
gaincal(vis=SB_cont_p2+'.ms', caltable=SB_p3, gaintype='T', spw=SB_contspws,
        refant=SB_refant, combine='spw', calmode='p', solint='120s', minsnr=3.,
        minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(SB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_scaled_selfcal_folder,prefix+'_SB_gain_p3_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=SB_cont_p2+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping,
         gaintable=[SB_p3], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p3 = prefix+'_scaled_ACASB_contp3'
os.system('rm -rf %s.ms*' % SB_cont_p3)
split(vis=SB_cont_p2+'.ms', outputvis=SB_cont_p3+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
delete_tclean_output(SB_cont_p3)
tclean_wrapper(vis=SB_cont_p3+'.ms', imagename = SB_cont_p3, mask=SB_mask,
               threshold = f'{6*0.055}mJy', deconvolver='multiscale', scales=SB_scales,
               savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p3+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
#J1604_scaled_ACASB_contp3.image
#Beam 0.516 arcsec x 0.401 arcsec (77.89 deg)
#Flux inside disk mask: 197.95 mJy
#Peak intensity of source: 26.40 mJy/beam
#rms: 5.43e-02 mJy/beam
#Peak SNR: 486.38


generate_image_png(SB_cont_p3+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],
                   save_folder=SB_scaled_selfcal_folder,
                   mask=SB_cont_p3+'.mask',noise_annulus=noise_annulus_SB)


SB_p4 = prefix+'_scaled_ACASB.p4'
os.system('rm -rf '+SB_p4)
gaincal(vis=SB_cont_p3+'.ms', caltable=SB_p4, gaintype='T', spw=SB_contspws,
        refant=SB_refant, combine='spw', calmode='p', solint='60s', minsnr=3.,
        minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p4,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(SB_p4,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_scaled_selfcal_folder,prefix+'_SB_gain_p4_phase_vs_time.png'))

applycal(vis=SB_cont_p3+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping,
         gaintable=[SB_p4], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p4 = prefix+'_scaled_ACASB_contp4'
os.system('rm -rf %s.ms*' % SB_cont_p4)
split(vis=SB_cont_p3+'.ms', outputvis=SB_cont_p4+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=SB_cont_p4+'.ms', imagename = SB_cont_p4, mask=SB_mask,
               threshold = f'{6*0.055}mJy', deconvolver='multiscale', scales=SB_scales,
               savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p4+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
#J1604_scaled_ACASB_contp4.image
#Beam 0.516 arcsec x 0.401 arcsec (77.89 deg)
#Flux inside disk mask: 198.00 mJy
#Peak intensity of source: 26.45 mJy/beam
#rms: 5.46e-02 mJy/beam
#Peak SNR: 484.72


generate_image_png(SB_cont_p4+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],
                   save_folder=SB_scaled_selfcal_folder,
                   mask=SB_cont_p4+'.mask',noise_annulus=noise_annulus_SB)


SB_p5 = prefix+'_scaled_ACASB.p5'
os.system('rm -rf '+SB_p5)
gaincal(vis=SB_cont_p4+'.ms', caltable=SB_p5, gaintype='T', spw=SB_contspws,
        refant=SB_refant, combine='spw', calmode='p', solint='20s', minsnr=3.,
        minblperant=4)
#quite some flagging (~10%?)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(SB_p5,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(SB_p5,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(SB_scaled_selfcal_folder,prefix+'_SB_gain_p5_phase_vs_time.png'))

applycal(vis=SB_cont_p4+'.ms', spw=SB_contspws, spwmap = SB_spw_mapping,
         gaintable=[SB_p5], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
SB_cont_p5 = prefix+'_scaled_ACASB_contp5'
os.system('rm -rf %s.ms*' % SB_cont_p5)
split(vis=SB_cont_p4+'.ms', outputvis=SB_cont_p5+'.ms', datacolumn='corrected')


""" Image the results; check the resulting map """
delete_tclean_output(SB_cont_p5)
tclean_wrapper(vis=SB_cont_p5+'.ms', imagename = SB_cont_p5, mask=SB_mask,
               threshold = f'{6*0.055}mJy', deconvolver='multiscale', scales=SB_scales,
               savemodel = 'modelcolumn', imsize=SB_imsize, cellsize=SB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(SB_cont_p5+'.image', disk_mask = SB_mask, noise_mask = noise_annulus_SB)
#J1604_scaled_ACASB_contp5.image
#Beam 0.516 arcsec x 0.401 arcsec (77.89 deg)
#Flux inside disk mask: 198.24 mJy
#Peak intensity of source: 26.54 mJy/beam
#rms: 5.50e-02 mJy/beam
#Peak SNR: 482.21

#the peak SNR decreased, but the gain solution showed some slope with time, so I
#decided to keep it

generate_image_png(SB_cont_p5+'.image',plot_sizes=image_png_plot_sizes['SB'],
                   color_scale_limits=[-3*rms_SB,10*rms_SB],
                   save_folder=SB_scaled_selfcal_folder,
                   mask=SB_cont_p5+'.mask',noise_annulus=noise_annulus_SB)


#plot amp vs time for a narrow uv range
non_self_caled_SB_vis = SB_cont_p0
self_caled_SB_visibilities = {'p1':SB_cont_p1,
                              'p2':SB_cont_p2,
                              'p3':SB_cont_p3,
                              'p4':SB_cont_p4,
                              'p5':SB_cont_p5}

SB_EBs = ('EB0','EB1')
SB_EB_spws = ('16,17,18,19','20,21,22,23') #fill in spws for each EB

for self_cal_step,self_caled_vis in self_caled_SB_visibilities.items():
    for EB_key,spw in zip(SB_EBs,SB_EB_spws):
        nametemplate = f'{prefix}_SB_{EB_key}_{self_cal_step}_compare_amp_vs_time'
        visibilities = [self_caled_vis+'.ms',non_self_caled_SB_vis+'.ms']
        plot_amp_vs_time_comparison(
                nametemplate=nametemplate,visibilities=visibilities,spw=spw,
                uvrange=uv_ranges['SB'],output_folder=SB_scaled_selfcal_folder)
#I don't really see a lot of change in thsese plots


all_SB_visibilities = self_caled_SB_visibilities.copy()
all_SB_visibilities['p0'] = SB_cont_p0

"""
if SB suffers from decoherence, then take an LB EB as flux reference; modify the code
below accordingly

If you haven't re-scaled the fluxes of LB EBs because all SB EBs had high decoherence,
check flux offsets of LB EBs here and correct them, if needed

"""

for self_cal_step,vis_name in all_SB_visibilities.items():
    #split out SB EBs
    vis_ms = vis_name+'.ms'
    nametemplate = vis_ms.replace('.ms','_EB')
    split_all_obs(msfile=vis_ms,nametemplate=nametemplate)
    exported_ms = []
    #we only consider SB, not ACA
    for i in range(number_of_EBs['ACA'],number_of_EBs['SB']+number_of_EBs['ACA']):
        EB_vis = f'{nametemplate}{i}.ms'
        export_MS(EB_vis) #export MS contents into Numpy save files
        exported_ms.append(EB_vis.replace('.ms','.vis.npz'))
    for i,exp_ms in zip(range(number_of_EBs['ACA'],number_of_EBs['SB']+number_of_EBs['ACA']),
                        exported_ms):
        png_filename = f'flux_comparison_ACASB_EB{i}_{self_cal_step}_to_{flux_ref_EB}.png'
        plot_label = os.path.join(SB_scaled_selfcal_folder,png_filename)
        estimate_flux_scale(reference=f'{prefix}_{flux_ref_EB}_initcont_shift.vis.npz',
                            comparison=exp_ms,incl=incl,PA=PA,plot_label=plot_label)
    fluxscale = [1.,]*number_of_EBs['SB']
    plot_label = os.path.join(SB_scaled_selfcal_folder,
                              f'deprojected_vis_profiles_SB_{self_cal_step}.png')
    plot_deprojected(filelist=exported_ms,fluxscale=fluxscale, PA=PA, incl=incl,
                     show_err=True,plot_label=plot_label)

#Measurement set exported to J1604_scaled_ACASB_contp5_EB5.vis.npz
#The ratio of the fluxes of J1604_scaled_ACASB_contp5_EB4.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 1.00578
#The scaling factor for gencal is 1.003 for your comparison measurement
#The error on the weighted mean ratio is 5.645e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_scaled_ACASB_contp5_EB5.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 1.00480
#The scaling factor for gencal is 1.002 for your comparison measurement
#The error on the weighted mean ratio is 4.710e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor


#let's compare the self-caled ref SB with the non-self-caled LB:
SB_selfcaled_reference = f'{prefix}_scaled_ACASB_contp5_EB5.vis.npz'
for params in data_params_LB.values():
    estimate_flux_scale(reference=SB_selfcaled_reference,
                        comparison=prefix+'_'+params['name']+'_initcont_shift.vis.npz',
                        incl=incl, PA=PA,
                        plot_label=os.path.join(SB_scaled_selfcal_folder,
                                                'flux_comparison_'+params['name']+f'_to_{SB_selfcaled_reference}.png'))
#The ratio of the fluxes of J1604_LB_EB0_initcont_shift.vis.npz to
#J1604_scaled_ACASB_contp5_EB5.vis.npz is 1.03486

#The ratio of the fluxes of J1604_LB_EB1_initcont_shift.vis.npz to
#J1604_scaled_ACASB_contp5_EB5.vis.npz is 1.03028

#The ratio of the fluxes of J1604_LB_EB2_initcont_shift.vis.npz to
#J1604_scaled_ACASB_contp5_EB5.vis.npz is 1.06048

#still strong gradient with uv dist

#compare to what we had before self-cal:
    
#The ratio of the fluxes of J1604_LB_EB0_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 1.04415

#The ratio of the fluxes of J1604_LB_EB1_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 1.03798

#The ratio of the fluxes of J1604_LB_EB2_initcont_shift.vis.npz to
#J1604_SB_EB1_initcont_shift.vis.npz is 1.06838


#pretty much the same as before self-cal... let's see if LB self-cal can fix it...


"""SELF-CAL COMBINED DATA"""
LB_scaled_selfcal_folder = get_figures_folderpath('12_scaled_selfcal_ACASBLB_figures')
make_figures_folder(LB_scaled_selfcal_folder)

""" Merge the SB self-cal'ed ms with LB ms"""
LB_cont_p0 = prefix+'_scaled_ACASBLB_contp0'
os.system('rm -rf %s.ms*' % LB_cont_p0)

concat(vis=[SB_cont_p5+'.ms']+[f'{prefix}_LB_EB0_initcont_shift_rescaled.ms',
                               f'{prefix}_LB_EB1_initcont_shift_rescaled.ms',
                               f'{prefix}_LB_EB2_initcont_shift.ms',],
            concatvis=LB_cont_p0+'.ms', dirtol='0.1arcsec', copypointing=False)

listobs(
    vis=LB_cont_p0+'.ms',
    listfile=LB_cont_p0+'.ms.txt',
    overwrite=True,
)

""" clean down to ~6 sigma"""
delete_tclean_output(LB_cont_p0)
tclean_wrapper(vis=LB_cont_p0+'.ms', imagename = LB_cont_p0, mask=LB_mask,
               threshold = f'{6*0.04}mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p0+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
#J1604_scaled_ACASBLB_contp0.image
#Beam 0.155 arcsec x 0.128 arcsec (-77.55 deg)
#Flux inside disk mask: 203.54 mJy
#Peak intensity of source: 5.31 mJy/beam
#rms: 3.82e-02 mJy/beam
#Peak SNR: 139.10


rms_LB = imstat(imagename = LB_cont_p0+'.image', region = noise_annulus_LB)['rms'][0]
generate_image_png(LB_cont_p0+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_scaled_selfcal_folder,
                   mask=LB_cont_p0+'.mask',noise_annulus=noise_annulus_LB)


LB_p1 = prefix+'_scaled_ACASBLB.p1'
os.system('rm -rf '+LB_p1)
#try gaintype='G', and if there are many flagged solutions, change it to 'T'
gaincal(vis=LB_cont_p0+'.ms', caltable=LB_p1, gaintype='G', spw=LB_contspws,
        refant=LB_refant, combine='scan,spw', calmode='p', solint='inf', minsnr=2.,
        minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(LB_p1,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_scaled_selfcal_folder,prefix+'_LB_gain_p1_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p0+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_p1], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p1 = prefix+'_scaled_ACASBLB_contp1'
os.system('rm -rf %s.ms*' % LB_cont_p1)
split(vis=LB_cont_p0+'.ms', outputvis=LB_cont_p1+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
delete_tclean_output(LB_cont_p1)
tclean_wrapper(vis=LB_cont_p1+'.ms', imagename = LB_cont_p1, mask=LB_mask,
               threshold = f'{6*0.039}mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p1+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
#J1604_scaled_ACASBLB_contp1.image
#Beam 0.155 arcsec x 0.128 arcsec (-77.55 deg)
#Flux inside disk mask: 204.10 mJy
#Peak intensity of source: 5.31 mJy/beam
#rms: 3.78e-02 mJy/beam
#Peak SNR: 140.71


generate_image_png(LB_cont_p1+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_scaled_selfcal_folder,
                   mask=LB_cont_p1+'.mask',noise_annulus=noise_annulus_LB)


""" Second round of phase-only self-cal (LB only) """
LB_p2 = prefix+'_scaled_ACASBLB.p2'
os.system('rm -rf '+LB_p2)
gaincal(vis=LB_cont_p1+'.ms', caltable=LB_p2, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw,scan', calmode='p', solint='360s', minsnr=2.,
        minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(LB_p2,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_scaled_selfcal_folder,prefix+'_LB_gain_p2_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p1+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_p2], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p2 = prefix+'_scaled_ACASBLB_contp2'
os.system('rm -rf %s.ms*' % LB_cont_p2)
split(vis=LB_cont_p1+'.ms', outputvis=LB_cont_p2+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
delete_tclean_output(LB_cont_p2)
tclean_wrapper(vis=LB_cont_p2+'.ms', imagename = LB_cont_p2, mask=LB_mask,
               threshold = f'{6*0.03}mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p2+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
#J1604_scaled_ACASBLB_contp2.image
#Beam 0.155 arcsec x 0.128 arcsec (-77.55 deg)
#Flux inside disk mask: 202.84 mJy
#Peak intensity of source: 5.54 mJy/beam
#rms: 2.93e-02 mJy/beam
#Peak SNR: 189.28


generate_image_png(LB_cont_p2+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_scaled_selfcal_folder,
                   mask=LB_cont_p2+'.mask',noise_annulus=noise_annulus_LB)

""" Third round of phase-only self-cal (LB only) """
"""
Check scan length to decide whether to combine scans. If scans are 2 min,
do not combine them. If they are shorter, combine scans here
"""
#LB scan length is 2-3 minutes, so we do not combine scanes
LB_p3 = prefix+'_scaled_ACASBLB.p3'
os.system('rm -rf '+LB_p3)
gaincal(vis=LB_cont_p2+'.ms', caltable=LB_p3, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw', calmode='p', solint='120s', minsnr=2.,
        minblperant=4)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw')
""" Print calibration png file """
plotms(LB_p3,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_scaled_selfcal_folder,prefix+'_LB_gain_p3_phase_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p2+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_p3], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_p3 = prefix+'_scaled_ACASBLB_contp3'
os.system('rm -rf %s.ms*' % LB_cont_p3)
split(vis=LB_cont_p2+'.ms', outputvis=LB_cont_p3+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
delete_tclean_output(LB_cont_p3)
tclean_wrapper(vis=LB_cont_p3+'.ms', imagename = LB_cont_p3, mask=LB_mask,
               threshold = f'{6*0.029}mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p3+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
#J1604_scaled_ACASBLB_contp3.image
#Beam 0.155 arcsec x 0.128 arcsec (-77.55 deg)
#Flux inside disk mask: 202.86 mJy
#Peak intensity of source: 5.60 mJy/beam
#rms: 2.87e-02 mJy/beam
#Peak SNR: 195.21


generate_image_png(LB_cont_p3+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_scaled_selfcal_folder,
                   mask=LB_cont_p3+'.mask',noise_annulus=noise_annulus_LB)


""" Clean down to 1 sigma for amplitude self-cal"""
delete_tclean_output(LB_cont_p3)
tclean_wrapper(vis=LB_cont_p3+'.ms', imagename = LB_cont_p3, mask=LB_mask,
               threshold = '0.029mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_p3+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
#J1604_scaled_ACASBLB_contp3.image
#Beam 0.149 arcsec x 0.118 arcsec (-78.44 deg)
#Flux inside disk mask: 199.64 mJy
#Peak intensity of source: 5.32 mJy/beam
#rms: 2.71e-02 mJy/beam
#Peak SNR: 196.28


""" Amplitude self-cal"""
LB_ap0 = prefix+'_scaled_ACASBLB.ap0'
os.system('rm -rf '+LB_ap0)
gaincal(vis=LB_cont_p3+'.ms', caltable=LB_ap0, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw, scan', calmode='ap', solint='inf', minsnr=5.0,
        minblperant=4, solnorm=False)

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_ap0,xaxis='time', yaxis='GainPhase',iteraxis='spw')
plotms(LB_ap0,xaxis='time', yaxis='GainAmp',iteraxis='spw')

""" Print calibration png file """
plotms(LB_ap0,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_scaled_selfcal_folder,prefix+'_LB_gain_ap0_phase_vs_time.png'))
plotms(LB_ap0,xaxis='time', yaxis='GainAmp',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_scaled_selfcal_folder,prefix+'_LB_gain_ap0_amp_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_p3+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_ap0], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_ap0 = prefix+'_scaled_ACASBLB_contap0'
os.system('rm -rf %s.ms*' % LB_cont_ap0)
split(vis=LB_cont_p3+'.ms', outputvis=LB_cont_ap0+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
#again clean down to 1 sigma
delete_tclean_output(LB_cont_ap0)
tclean_wrapper(vis=LB_cont_ap0+'.ms', imagename = LB_cont_ap0, mask=LB_mask,
               threshold = '0.027mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_ap0+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
#J1604_scaled_ACASBLB_contap0.image
#Beam 0.144 arcsec x 0.117 arcsec (-82.19 deg)
#Flux inside disk mask: 199.94 mJy
#Peak intensity of source: 5.10 mJy/beam
#rms: 2.53e-02 mJy/beam
#Peak SNR: 201.58


generate_image_png(LB_cont_ap0+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_scaled_selfcal_folder,
                   mask=LB_cont_ap0+'.mask',noise_annulus=noise_annulus_LB)

""" Try ampl self-cal on with shorter sol int (for reference, scan length is 2-3 min)"""
LB_ap1 = prefix+'_scaled_ACASBLB.ap1'
os.system('rm -rf '+LB_ap1)
gaincal(vis=LB_cont_ap0+'.ms', caltable=LB_ap1, gaintype='T', spw=LB_contspws,
        refant=LB_refant, combine='spw, scan', calmode='ap', solint='360s', minsnr=5.0,
        minblperant=4, solnorm=False)
#some flagging, but no excessive

""" Inspect gain tables interactively and decide whether to manually flag something"""
plotms(LB_ap1,xaxis='time', yaxis='GainPhase',iteraxis='spw')
plotms(LB_ap1,xaxis='time', yaxis='GainAmp',iteraxis='spw')
#quite some amps below 0.8 and above 1.2, manually flagged

""" Print calibration png file """
plotms(LB_ap1,xaxis='time', yaxis='GainPhase',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_scaled_selfcal_folder,prefix+'_LB_gain_ap1_phase_vs_time.png'))
plotms(LB_ap1,xaxis='time', yaxis='GainAmp',iteraxis='spw',exprange='all',
       overwrite=True,showgui=False,
       plotfile=os.path.join(LB_scaled_selfcal_folder,prefix+'_LB_gain_ap1_amp_vs_time.png'))

""" Apply the solutions """
applycal(vis=LB_cont_ap0+'.ms', spw=LB_contspws, spwmap = LB_spw_mapping,
         gaintable=[LB_ap1], interp='linearPD', calwt=True, applymode='calonly')

""" Split off a corrected MS """
LB_cont_ap1 = prefix+'_scaled_ACASBLB_contap1'
os.system('rm -rf %s.ms*' % LB_cont_ap1)
split(vis=LB_cont_ap0+'.ms', outputvis=LB_cont_ap1+'.ms', datacolumn='corrected')

""" Image the results; check the resulting map """
tclean_wrapper(vis=LB_cont_ap1+'.ms', imagename = LB_cont_ap1, mask=LB_mask,
               threshold = '0.027mJy', deconvolver='multiscale', scales=LB_scales,
               savemodel = 'modelcolumn', imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_ap1+'.image', disk_mask = LB_mask, noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_ap1+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=LB_scaled_selfcal_folder,
                   mask=LB_cont_ap1+'.mask',noise_annulus=noise_annulus_LB)
#J1604_scaled_ACASBLB_contap1.image
#Beam 0.143 arcsec x 0.117 arcsec (-83.50 deg)
#Flux inside disk mask: 200.01 mJy
#Peak intensity of source: 5.01 mJy/beam
#rms: 2.49e-02 mJy/beam
#Peak SNR: 201.21



self_caled_LB_visibilities = {'p1':LB_cont_p1,
                              'p2':LB_cont_p2,
                              'p3':LB_cont_p3,
                              'ap0':LB_cont_ap0,
                              'ap1':LB_cont_ap1}

for vis in self_caled_LB_visibilities.values(): 
    listobs(vis=vis+'.ms',listfile=vis+'ms.txt',overwrite=True)


LB_EBs = ('EB0','EB1','EB2')
LB_EB_spws = ('24,25,26,27','28,29,30,31','32,33,34,35') #fill out by referring to listobs output

for self_cal_step,self_caled_vis in self_caled_LB_visibilities.items():
    for EB_key,spw in zip(LB_EBs,LB_EB_spws):
        nametemplate = f'{prefix}_LB_{EB_key}_{self_cal_step}_compare_amp_vs_time'
        visibilities = [self_caled_vis+'.ms',LB_cont_p0+'.ms']
        plot_amp_vs_time_comparison(
                nametemplate=nametemplate,visibilities=visibilities,spw=spw,
                uvrange=uv_ranges['LB'],output_folder=LB_scaled_selfcal_folder)


#flux_comparison_ref_EB is set to the EB of the combined ACASBLB data that corresponds
#to flux_ref_EB
#However, if flux_ref_EB is not an SB EB, you should set flux_comparison_ref_EB to
#an SB EB, since only SB has overlapping baselines with both ACA and LB
#at this point in the script, SB should be correctly scaled and decoherence removed,
#so it should be ok to use SB as a reference
flux_comparison_ref_EB = 5
total_number_of_EBs = number_of_EBs['ACA']+number_of_EBs['SB']+number_of_EBs['LB']

for self_cal_step,vis in self_caled_LB_visibilities.items():
    nametemplate = f'{prefix}_scaled_ACASBLB_cont{self_cal_step}_EB'
    split_all_obs(msfile=vis+'.ms',nametemplate=nametemplate)
    for i in range(total_number_of_EBs):
        export_MS(f'{nametemplate}{i}.ms')
    reference = f'{nametemplate}{flux_comparison_ref_EB}.vis.npz'
    for i in range(total_number_of_EBs):
        output = f'flux_comparison_EB{i}_to_EB{flux_comparison_ref_EB}'\
                       +f'_ACASBLB_{self_cal_step}.png'
        plot_label = os.path.join(LB_scaled_selfcal_folder,output)
        estimate_flux_scale(reference=reference,
                            comparison=f'{nametemplate}{i}.vis.npz',
                            incl=incl, PA=PA,#uvbins = np.arange(40.,300.,20.),
                            plot_label=plot_label)
    filelist = [f'{nametemplate}{i}.vis.npz' for i in range(total_number_of_EBs)]
    fluxscale = [1.,]*total_number_of_EBs
    plot_deprojected(filelist=filelist,fluxscale=fluxscale, PA=PA, incl=incl,
                      show_err=True,
                      plot_label=os.path.join(LB_scaled_selfcal_folder,
                                              f'deprojected_vis_profiles_ACASBLB_{self_cal_step}.png'))
#Measurement set exported to J1604_scaled_ACASBLB_contap1_EB8.vis.npz
#The ratio of the fluxes of J1604_scaled_ACASBLB_contap1_EB0.vis.npz to
#J1604_scaled_ACASBLB_contap1_EB5.vis.npz is 0.98144
#The scaling factor for gencal is 0.991 for your comparison measurement
#The error on the weighted mean ratio is 4.278e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_scaled_ACASBLB_contap1_EB1.vis.npz to
#J1604_scaled_ACASBLB_contap1_EB5.vis.npz is 1.00219
#The scaling factor for gencal is 1.001 for your comparison measurement
#The error on the weighted mean ratio is 4.007e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_scaled_ACASBLB_contap1_EB2.vis.npz to
#J1604_scaled_ACASBLB_contap1_EB5.vis.npz is 1.00739
#The scaling factor for gencal is 1.004 for your comparison measurement
#The error on the weighted mean ratio is 2.592e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_scaled_ACASBLB_contap1_EB3.vis.npz to
#J1604_scaled_ACASBLB_contap1_EB5.vis.npz is 0.98581
#The scaling factor for gencal is 0.993 for your comparison measurement
#The error on the weighted mean ratio is 3.536e-03, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_scaled_ACASBLB_contap1_EB4.vis.npz to
#J1604_scaled_ACASBLB_contap1_EB5.vis.npz is 0.99907
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 5.591e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_scaled_ACASBLB_contap1_EB5.vis.npz to
#J1604_scaled_ACASBLB_contap1_EB5.vis.npz is 1.00000
#The scaling factor for gencal is 1.000 for your comparison measurement
#The error on the weighted mean ratio is 4.675e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_scaled_ACASBLB_contap1_EB6.vis.npz to
#J1604_scaled_ACASBLB_contap1_EB5.vis.npz is 0.99180
#The scaling factor for gencal is 0.996 for your comparison measurement
#The error on the weighted mean ratio is 9.482e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_scaled_ACASBLB_contap1_EB7.vis.npz to
#J1604_scaled_ACASBLB_contap1_EB5.vis.npz is 0.99608
#The scaling factor for gencal is 0.998 for your comparison measurement
#The error on the weighted mean ratio is 8.595e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor

#The ratio of the fluxes of J1604_scaled_ACASBLB_contap1_EB8.vis.npz to
#J1604_scaled_ACASBLB_contap1_EB5.vis.npz is 0.99593
#The scaling factor for gencal is 0.998 for your comparison measurement
#The error on the weighted mean ratio is 8.280e-04, although it's likely that
#the weights in the measurement sets are too off by some constant factor



##### end of self-cal of flux-scaled data ###############

""" Split out final continuum ms table, with a 30s timebin
"""
LB_cont_averaged = prefix+'_time_ave_continuum'
os.system(f'rm -rf {LB_cont_averaged}.ms*')
split(vis=LB_cont_ap1+'.ms', outputvis=LB_cont_averaged+'.ms', datacolumn='data',
      keepflags=False, timebin='30s')


"""
Now apply these solutions to the line data
"""
calibrate_linedata_folder = get_figures_folderpath('13_apply_cal_to_lines')
make_figures_folder(calibrate_linedata_folder)

""" Check that lines are not flagged in not averaged data"""
for params in data_params.values():
    plotms(vis=params['vis'],
            xaxis='channel',
            yaxis='amplitude',
            field=params['field'],
            ydatacolumn='data',
            avgtime='1e8',
            avgscan=True,
            avgbaseline=True,
            coloraxis='corr',
            iteraxis='spw',
            showgui = False,
            exprange='all',
            plotfile=os.path.join(calibrate_linedata_folder,
                                  prefix+'_'+params['name']+'_chan-v-amp_preselfcal_after_flagging.png')
            )

##################
#shift phase center if you did it for continuum
for params in data_params.values():
    vis = params['vis']
    outputvis = vis[:-3] + '_pcshift.ms'
    fixvis(vis=vis,outputvis=outputvis,field=params['field'],
           phasecenter=fitted_disk_center)

#####################################

""" Apply gaintables of individual EBs"""
for params in data_params.values():
    single_EB_p1 = prefix+'_'+params['name']+'_initcont.p1'
    vis = params['vis'][:-3] + '_pcshift.ms'
    applycal(vis=vis,spw='0~3',spwmap=[0,0,0,0],gaintable=[single_EB_p1],
             interp='linearPD', applymode='calonly', calwt=True)
    split(vis=vis,
          outputvis=prefix+'_'+params['name']+'_no_ave_selfcal.ms',
          datacolumn='corrected')

###
# ALIGN DATA: we re-align the no_ave data, as we have done for the "initcont" ms tables.
# We go from *_no_ave_selfcal.ms to *_no_ave_shift.ms

reference_ms = {'LB':reference_for_LB_alignment,
                'SB':reference_for_SB_alignment,
                'ACA':reference_for_ACA_alignment}
for params in data_params.values():
    unshifted_ms = f'{prefix}_{params["name"]}_no_ave_selfcal.ms'
    array_key,_ = params['name'].split('_') #LB, SB or ACA
    offset = alignment_offsets[params['name']]
    #npix and cell_size are not needed because we do not fit any offset
    alignment.align_measurement_sets(
            reference_ms=reference_ms[array_key],align_ms=[unshifted_ms],
            align_offsets=[offset],npix=None,cell_size=None)

###


"""
If you have re-scaled fluxes, you need to re-scale the *no_ave* EBs as well, for example:
rescale_flux(f'{prefix}_LB_EB0_no_ave_selfcal_shift.ms', [1.044])
"""
rescale_flux(vis=prefix+'_SB_EB0_no_ave_selfcal_shift.ms', gencalparameter=[0.962])
rescale_flux(vis=prefix+'_LB_EB0_no_ave_selfcal_shift.ms', gencalparameter=[1.032])
rescale_flux(vis=prefix+'_LB_EB1_no_ave_selfcal_shift.ms', gencalparameter=[1.032])


""" Concat not averaged ACA data """
ACA_combined = prefix+'_ACA_no_ave_concat'
os.system('rm -rf %s.ms*' % ACA_combined)
concat(vis=[f'{prefix}_ACA_EB{i}_no_ave_selfcal_shift.ms' for i in range(number_of_EBs['ACA'])],
       concatvis=ACA_combined+'.ms', dirtol='0.1arcsec', copypointing=False)

listobs(vis=ACA_combined+'.ms',listfile=ACA_combined+'.ms.txt',overwrite=True)

applycal(vis=ACA_combined+'.ms', spw='0~15',
         gaintable=[prefix+'_ACA.p1',prefix+'_ACA.p2'],
         spwmap = [list(range(16)),ACA_spw_mapping],
         interp=['linear','linearPD'], calwt=True,
         applymode='calonly',flagbackup=False)

os.system('rm -rf '+prefix+'_ACA_no_ave_selfcal.ms*')
split(vis=ACA_combined+'.ms', outputvis=prefix+'_ACA_no_ave_selfcal.ms',
      datacolumn='corrected')

""" Concat not averaged SB data """
SB_combined = prefix+'_ACASB_no_ave_concat'
os.system('rm -rf %s.ms*' % SB_combined)

concat(vis=[f'{prefix}_ACA_no_ave_selfcal.ms',
            f'{prefix}_SB_EB0_no_ave_selfcal_shift_rescaled.ms',
            f'{prefix}_SB_EB1_no_ave_selfcal_shift.ms'],
       concatvis=SB_combined+'.ms', dirtol='0.1arcsec', copypointing=False)


listobs(vis=SB_combined+'.ms',listfile=SB_combined+'.ms.txt',overwrite=True)

#Be careful here to be sure to apply the right gain tables, in particular,
#if you did the SB self-cal twice (e.g. SB selfcal #1 on flux-unscaled MS, SB selfcal
# #2 on scaled MS)
applycal(vis=SB_combined+'.ms', spw='0~23',
         gaintable=[f'{prefix}_scaled_ACASB.p{i}' for i in range(1,6)],
         spwmap = [SB_spw_mapping]*5,interp=['linearPD']*5, calwt=True,
         applymode='calonly',flagbackup=False)

os.system('rm -rf '+prefix+'_ACASB_no_ave_selfcal.ms*')
split(vis=SB_combined+'.ms', outputvis=prefix+'_ACASB_no_ave_selfcal.ms',
      datacolumn='corrected')

""" Concat not averaged LB data """

LB_combined = prefix+'_ACASBLB_no_ave_concat'
os.system('rm -rf %s.ms*' % LB_combined)

concat(vis=[f'{prefix}_ACASB_no_ave_selfcal.ms']
           +[f'{prefix}_LB_EB0_no_ave_selfcal_shift_rescaled.ms',
             f'{prefix}_LB_EB1_no_ave_selfcal_shift_rescaled.ms',
             f'{prefix}_LB_EB2_no_ave_selfcal_shift.ms'],
       concatvis=LB_combined+'.ms', dirtol='0.1arcsec', copypointing=False)

listobs(vis=LB_combined+'.ms',listfile=LB_combined+'.ms.txt',overwrite=True)

applycal(vis=LB_combined+'.ms', spw='0~35',
         gaintable=[prefix+'_scaled_ACASBLB.p1',prefix+'_scaled_ACASBLB.p2',
                    prefix+'_scaled_ACASBLB.p3',prefix+'_scaled_ACASBLB.ap0',
                    prefix+'_scaled_ACASBLB.ap1'],
         spwmap = [LB_spw_mapping]*5,interp=['linearPD']*5,
         calwt=True, applymode='calonly',flagbackup=False)

ACASBLB_no_ave_final = f'{prefix}_ACASBLB_no_ave_selfcal_time_ave.ms'
os.system(f'rm -rf {ACASBLB_no_ave_final}*')
""" time average of 30s, tests show there is no different with data without time average """
split(vis=LB_combined+'.ms', outputvis=ACASBLB_no_ave_final,
      datacolumn='corrected', timebin = '30s', keepflags=False)

# Check that solutions have been applied correctly by flagging the line data, averaging and imaging continuum
# continuum has to be the same imaged in the last step of the self-cal
complete_dataset_dict = {'vis' : ACASBLB_no_ave_final,
                         'name' : 'ACASBLB_concat',
                         'field' : fields['LB'],
                         'line_spws': np.array([0,2,3,
                                                4,6,7,
                                                8,10,11,
                                                12,14,15,
                                                16,18,19,
                                                20,22,23,
                                                24,26,27,
                                                28,30,31,
                                                32,34,35]), # list of spws containing lines
                         'line_freqs': np.array([rest_freq_13CO,rest_freq_CS,rest_freq_12CO]*9), #frequencies (Hz) corresponding to line_spws
                         'cont_spws': None,
                         'width_array': None,
                         }

#use the output of get_flagchannels at the beginning of the script to define fitspw
# Flagchannels input string for LB_EB0: '0:834~3002, 2:798~3046, 3:782~3049'
# Flagchannels input string for LB_EB1: '0:834~3002, 2:798~3046, 3:782~3049'
# Flagchannels input string for LB_EB2: '0:834~3002, 2:798~3046, 3:781~3049'
# Flagchannels input string for SB_EB0: '0:838~3006, 2:793~3042, 3:790~3058'
# Flagchannels input string for SB_EB1: '0:837~3005, 2:793~3042, 3:788~3056'
# Flagchannels input string for ACA_EB0: '0:963~3131, 2:921~3170, 3:915~3183'
# Flagchannels input string for ACA_EB1: '0:963~3131, 2:921~3170, 3:915~3182'
# Flagchannels input string for ACA_EB2: '0:963~3131, 2:921~3169, 3:915~3183'
# Flagchannels input string for ACA_EB3: '0:963~3131, 2:920~3169, 3:916~3184'
fitspw =  '0:963~3131, 1:0, 2:921~3170, 3:915~3183,'\
         +'4:963~3131, 5:0, 6:921~3170, 7:915~3182,'\
         +'8:963~3131, 9:0, 10:921~3169, 11:915~3183,'\
         +'12:963~3131, 13:0, 14:920~3169, 15:916~3184,'\
         +'16:836~3006, 17:0, 18:793~3042, 19:790~3058,'\
         +'20:837~3005, 21:0, 22:793~3042, 23:788~3056,'\
         +'24:834~3002, 25:0, 26:798~3046, 27:782~3049,'\
         +'28:834~3002, 29:0, 30:798~3046, 31:782~3049,'\
         +'32:834~3002, 33:0, 34:798~3046, 35:781~3049'

avg_cont(ms_dict=complete_dataset_dict,output_prefix=prefix,flagchannels=fitspw,
         contspws=complete_dataset_dict['cont_spws'],
         width_array=complete_dataset_dict['width_array'])

# image the "avg then cal" with same parameters as in last step of self-cal
tclean_wrapper(vis=LB_cont_averaged+'.ms',
               imagename = LB_cont_averaged+'_image', mask=LB_mask,
               threshold = '0.027mJy', deconvolver='multiscale', scales=LB_scales,
               imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(LB_cont_averaged+'_image'+'.image', disk_mask = LB_mask,
             noise_mask = noise_annulus_LB)
generate_image_png(LB_cont_averaged+'_image'+'.image',
                   plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=calibrate_linedata_folder)

# image the "cal then avg" with same parameters as in last step of self-cal
complete_dataset_image = prefix+'_'+complete_dataset_dict['name']+'_initcont_image'
tclean_wrapper(vis=prefix+'_'+complete_dataset_dict['name']+'_initcont.ms',
               imagename = complete_dataset_image, mask=LB_mask,
               threshold = '0.027mJy', deconvolver='multiscale', scales=LB_scales,
               imsize=LB_imsize, cellsize=LB_cellsize,
               robust=0.5, interactive=False, parallel=use_parallel, gridder='mosaic')
estimate_SNR(complete_dataset_image+'.image', disk_mask = LB_mask,
             noise_mask = noise_annulus_LB)
generate_image_png(complete_dataset_image+'.image',plot_sizes=image_png_plot_sizes['LB'],
                   color_scale_limits=[-3*rms_LB,10*rms_LB],
                   save_folder=calibrate_linedata_folder)

# Plot ratio of "cal then avg" to "avg then cal".
#It should be equal to ~one (only difference being the time average):
ref_image = LB_cont_averaged+'_image'+'.image'
os.system('rm -rf '+complete_dataset_image+'.ratio')
immath(imagename=[ref_image,complete_dataset_image+'.image'],mode='evalexpr',
       outfile=complete_dataset_image+'.ratio',
       expr='iif(IM0 > 3*'+str(rms_LB)+', IM1/IM0, 0)')
generate_image_png(f'{complete_dataset_image}.ratio',
                   plot_sizes=[2*mask_semimajor,2*mask_semimajor],
                   color_scale_limits=[0.5,1.5],image_units='ratio',
                   save_folder=calibrate_linedata_folder)


# Do continuum subtraction
contsub_vis = f'{ACASBLB_no_ave_final}.contsub'
os.system(f'rm -rf {contsub_vis}*')
uvcontsub(vis=ACASBLB_no_ave_final, spw='0~35', fitspw=fitspw,
          excludechans=True, solint='int', fitorder=1, want_cont=False)

# Split final ms table into separate spws for 12CO, 13CO, CS and continuum

#12CO
vis_12CO = ACASBLB_no_ave_final[:-3]+'_12CO.ms'
os.system(f'rm -rf {vis_12CO}*')
spw_12CO = '3,7,11,15,19,23,27,31,35'
split(vis=ACASBLB_no_ave_final,outputvis=vis_12CO,spw=spw_12CO,
      datacolumn='data', keepflags=False)
split(vis=contsub_vis,outputvis=f'{vis_12CO}.contsub',spw=spw_12CO,
      datacolumn='data', keepflags=False)

#13CO
vis_13CO = ACASBLB_no_ave_final[:-3]+'_13CO.ms'
os.system(f'rm -rf {vis_13CO}*')
spw_13CO = '0,4,8,12,16,20,24,28,32'
split(vis=ACASBLB_no_ave_final,outputvis=vis_13CO,spw=spw_13CO,
      datacolumn='data', keepflags=False)
split(vis=contsub_vis,outputvis=f'{vis_13CO}.contsub',spw=spw_13CO,
      datacolumn='data', keepflags=False)

#CS
vis_CS = ACASBLB_no_ave_final[:-3]+'_CS.ms'
os.system(f'rm -rf {vis_CS}*')
spw_CS = '2,6,10,14,18,22,26,30,34'
split(vis=ACASBLB_no_ave_final,outputvis=vis_CS,spw=spw_CS,
      datacolumn='data', keepflags=False)
split(vis=contsub_vis,outputvis=f'{vis_CS}.contsub',spw=spw_CS,
      datacolumn='data', keepflags=False)

#continuum spw
vis_continuum = ACASBLB_no_ave_final[:-3]+'_contspw.ms'
os.system(f'rm -rf {vis_continuum}*')
spw_continuum = '1,5,9,13,17,21,25,29,33'
split(vis=ACASBLB_no_ave_final,outputvis=vis_continuum,spw=spw_continuum,
      datacolumn='data', keepflags=False)
split(vis=contsub_vis,outputvis=f'{vis_continuum}.contsub',spw=spw_continuum,
      datacolumn='data', keepflags=False)

for vis in (vis_12CO,vis_13CO,vis_CS):
    listobs(vis=f'{vis}.contsub',listfile=f'{vis}.contsub.txt',overwrite=True)
listobs(vis=vis_continuum,listfile=f'{vis_continuum}.txt',overwrite=True)